Java 下载后文件已损坏

Java 下载后文件已损坏,java,apache-commons,Java,Apache Commons,我正在开发一个Java实用程序,它可以从Jira用户故事下载附件。我正在使用Jira Rest API获取附件信息,并使用URL尝试下载附件 在我的程序中,我使用apachecommons io库下载文件。然而,一旦下载文件,我可以看到文件已损坏 代码段: URL url = new URL(sourceURL); String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());

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

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

意见:

  • 所有下载的文件大小相同(23KB)
  • 使用相同的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);
    

    你看过文件的内容了吗?“里面可能只有一条错误信息吗?”亨利。你说得对。我错过了。有一条错误消息要求我登录。下载的内容是带有错误消息的HTML页面。您可以回答自己的问题,将上次编辑的内容放在答案中,以便问题不再打开。谢谢。我会的。我们需要在这里提供什么源URL?