下载后文件损坏

Files are corrupted after downloading

我正在开发一个 Java 实用程序,它可以从 Jira 用户故事下载附件。我正在使用 Jira Rest API 获取附件信息并使用 URLs,我正在尝试下载附件。

在我的程序中,我使用 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 文件)

观察:

  1. 所有下载的文件大小相同 (23 KB)
  2. 使用相同的URL,从浏览器我可以成功下载文件

我在这里缺少什么?

我可以通过以下更改解决问题:

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);