我正在开发一个 Java 实用程序,它可以从 Jira 用户故事下载附件。我正在使用 Jira Rest API 获取附件信息并使用 URL,我正在尝试下载附件。
在我的程序中,我使用 Apache commons-io 库来下载文件。但是,一旦下载了文件,我就可以看到文件已损坏。
代码片段:
URL url = new URL(sourceURL);
String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
File targetPath = new File(targetDirectory + File.separator + fileName);
FileUtils.copyURLToFile(url, targetPath);
我下载的网站需要身份验证。因此,除了上述内容之外,我还添加了身份验证信息:
Authenticator.setDefault(new CustomAuthenticator(jiraUserName, jiraPassword));
public class CustomAuthenticator extends Authenticator {
private String username = null;
private String password = null;
public CustomAuthenticator(String jiraUserName, String jiraPassword) {
this.username = jiraUserName;
this.password = jiraPassword;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
添加身份验证信息后,我得到了相同的结果。我正在下载多种类型的附件(附件可以是 pdf、xlsx、png 或 jpg 文件)
观察结果:
- 所有下载的文件大小相同 (23 KB)
- 使用相同的 URL,我可以从浏览器成功下载文件
我在这里缺少什么?
最佳答案
我可以通过以下更改解决该问题:
HttpURLConnection conn = (HttpURLConnection) new URL(sourceURL).openConnection();
String userpass = userName + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
Path targetPath = new File(targetDirectory + File.separator + fileName).toPath();
Files.copy(conn.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
关于java - 下载后文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689951/