2017-06-22 205 views
1

我正在从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文件)

观察:

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

我在这里失踪了什么?

+4

你看文件的内容是什么?它可能只是一个错误信息吗? – Henry

+0

@亨利。你是对的。我错过了。有一条错误消息要求我登录。下载的内容是带有错误消息的HTML页面。 – atom

+1

您可以回答自己的问题,将最后一次编辑放入答案中,以便问题不再打开。 – Henry

回答

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