简体   繁体   中英

Files are corrupted after downloading

I am working on a Java utility which can download the attachments from Jira user stories. I am using Jira Rest API to get the attachment information and using the URLs, I am trying to download the attachments.

In my program, I am using Apache commons-io library for downloading the files. However once files are downloaded I could see files are corrupted.

Code snippet:

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

Site from which I am downloading requires authentication. So along with the above I have added the authentication information:

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

After adding the authentication information also, I am getting the same result. I am downloading multiple types of attachment (An attachment could be pdf, xlsx, png or jpg files)

Observations:

  1. All downloaded files are of same size (23 KB)
  2. With the same URL, from browser I can download the files successfully

What I am missing here?

I am able to resolve the issue with the following changes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM