2017-06-22 201 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);