首页 > 解决方案 > IO Exception when i use "FileUtils.copyURLToFile(urlConnection.getURL(), exportFile);"

问题描述

Summary: I am trying to save the pdf file which will be generated from the API using FileUtils.copyURLToFile(urlConnection.getURL(), exportFile); but getting 401 error.

Error:

java.io.IOException: Server returned HTTP response code: 401 for URL: http://8901-7M0W2X2.KMX.LOCAL/api/comparison/cekdotljl8r98d827gw1y7xvh/result/pdf
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
    at org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1460)
    at sampleAPI.Main.main(Main.java:63)

I have authenticated the connection but getting the same error.

Written Code:

try {
    String name = "****";
    String password = "****";
    File exportFile = new File(
            "C:/New folder/result.pdf");
    String webPage = "http://8901-7M0W2X2.KMX.LOCAL:80/api/comparison/compare?file1=file:X/Letter_0.pdf&file1=file:X/Letter_2.pdf&result=pdf&visible=true&profile=MyStyle";
    String authString = name + ":" + password;
    System.out.println("auth string: " + authString);
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    System.out.println("Base64 encoded auth string: " + authStringEnc);
    URL url = new URL(webPage);
    URLConnection urlConnection = url.openConnection();
    urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

    FileUtils.copyURLToFile(urlConnection.getURL(), exportFile);

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Please provide your suggestion to fix the issue. Thanks!

标签: java

解决方案


我可以通过使用 InputStream 和 FileOutPutStream 来解决这个问题

response = urlConnection.getInputStream();
        fileOut = new FileOutputStream(outputFile);

        while ((i = response.read()) != -1) {
            fileOut.write(i);
        }
        fileOut.close();

谢谢!


推荐阅读