在Java中实现PDF文件下载的完整流程需要包含URL有效性验证、MIME类型设置和文件完整性检查三个关键步骤。
1、URL有效性验证
通过HttpURLConnection建立连接并检查响应码来验证URL有效性。设置合理的超时时间可以防止程序长时间阻塞,通常连接超时设为5秒,读取超时设为10秒。响应码为200表示URL有效且可访问,其他常见响应码如404表示资源不存在,403表示访问被拒绝。
2、MIME类型设置
PDF文件的正确MIME类型为"application/pdf"。在下载响应中必须设置Content-Type头字段为正确的MIME类型,确保浏览器能正确处理文件。同时通过Content-Disposition头指定下载文件名和行为3。
3、文件完整性检查
使用Apache PDFBox库的PDDocument类可以验证PDF文件的有效性。通过尝试加载PDF文件来检查其结构完整性,如果文件损坏或格式不正确会抛出异常。下载后还可以通过比较文件大小或计算MD5校验和来进一步验证文件完整性。
4、以下是一个完整的Java实现示例:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import org.apache.pdfbox.pdmodel.PDDocument;
public class PdfDownloadValidator {
/**
* 验证URL有效性
*/
public static boolean validateUrl(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.setRequestMethod("HEAD");
int responseCode = conn.getResponseCode();
String contentType = conn.getContentType();
return responseCode == 200 && "application/pdf".equals(contentType);
}
/**
* 下载PDF文件
*/
public static void downloadPdf(String urlStr, String filePath, String fileName)
throws IOException {
if (!validateUrl(urlStr)) {
throw new IOException("URL验证失败:无效的PDF链接");
}
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
try (InputStream in = conn.getInputStream();
FileOutputStream out = new FileOutputStream(filePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
/**
* 验证PDF文件完整性
*/
public static boolean validatePdfIntegrity(String filePath) {
try (PDDocument document = PDDocument.load(new File(filePath))) {
return document.getNumberOfPages() > 0;
} catch (Exception e) {
return false;
}
}
/**
* 计算文件MD5校验和
*/
public static String calculateFileMD5(String filePath) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
try (FileInputStream fis = new FileInputStream(filePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
public static void main(String[] args) {
try {
String pdfUrl = "http://example.com/document.pdf";
String savePath = "downloaded.pdf";
// 下载前验证URL
System.out.println("验证URL有效性...");
if (validateUrl(pdfUrl)) {
System.out.println("URL验证通过,开始下载");
// 下载文件
downloadPdf(pdfUrl, savePath, "document.pdf");
// 下载后验证文件完整性
System.out.println("验证文件完整性...");
if (validatePdfIntegrity(savePath)) {
System.out.println("PDF文件完整性验证通过");
String md5 = calculateFileMD5(savePath);
System.out.println("文件MD5校验和: " + md5);
} else {
System.out.println("PDF文件损坏或格式不正确");
}
} else {
System.out.println("URL无效或不是PDF文件");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven项目配置:
<code_start project_name=java_pdf下载验证 filename=pom.xml title=Maven项目配置 entrypoint=false runnable=false project_final_file=true>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>pdf-download-validator</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass>PdfDownloadValidator</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
<code_end>
该实现提供了完整的PDF下载验证流程:
- URL验证阶段通过HEAD请求检查链接状态和内容类型
- 下载过程设置适当的超时和用户代理
- 完整性检查使用PDFBox验证PDF结构
- 支持MD5校验和计算确保文件完整性
- 通过Maven管理项目依赖,确保PDFBox库正确引入

被折叠的 条评论
为什么被折叠?



