?Java??????????????????:
-
??HTTP?HTTPS??:???????HTTP?HTTPS??????,???????????????????????
-
????????:???????,????????(??MD5?SHA-1),????????????????????????????,???????????????
???????Java???????????????:
import java.io.*; import java.net.URL; import java.nio.file.Files; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class DownloadFileWithIntegrityCheck { public static void main(String[] args) throws IOException, NoSuchAlgorithmException { String fileUrl = "https://example.com/path/to/your/file.txt"; String outputFilePath = "downloaded_file.txt"; String expectedChecksum = "expected_checksum_value"; // ???????????????? downloadFileWithIntegrityCheck(fileUrl, outputFilePath, expectedChecksum); } public static void downloadFileWithIntegrityCheck(String fileUrl, String outputFilePath, String expectedChecksum) throws IOException, NoSuchAlgorithmException { URL url = new URL(fileUrl); try (InputStream inputStream = url.openStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } } String actualChecksum = calculateChecksum(outputFilePath, "MD5"); if (actualChecksum.equals(expectedChecksum)) { System.out.println("???????????"); } else { System.out.println("????????????"); Files.deleteIfExists(Paths.get(outputFilePath)); } } public static String calculateChecksum(String filePath, String algorithm) throws IOException, NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); try (InputStream inputStream = Files.newInputStream(Paths.get(filePath)); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { messageDigest.update(buffer, 0, bytesRead); } } byte[] checksumBytes = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : checksumBytes) { sb.append(String.format("x", b)); } return sb.toString(); } }
??????,????????URL????,???????MD5????????????????????????????????,?????????????????,???????????????