摘要:
我正在尝试保存使用FileUtils.copyURLToFile(urlConnection.getURL(), exportFile);
从API生成的pdf文件,但获取的是401 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)
我已经验证了连接,但收到相同的错误。
书面代码:
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();
}
请提供您解决此问题的建议。谢谢!
答案 0 :(得分:0)
我能够通过使用InputStream和FileOutPutStream来解决此问题
response = urlConnection.getInputStream();
fileOut = new FileOutputStream(outputFile);
while ((i = response.read()) != -1) {
fileOut.write(i);
}
fileOut.close();
谢谢!