我正在开发一个可以从Jira用户故事下载附件的Java实用程序。我正在使用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文件)
观察:
我在这里缺少什么?
答案 0 :(得分:1)
我可以通过以下更改解决问题:
HttpURLConnection conn = (HttpURLConnection) new URL(sourceURL).openConnection();
String userpass = jiraUserName + ":" + jiraPassword;
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);