java - 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!
解决方案
我可以通过使用 InputStream 和 FileOutPutStream 来解决这个问题
response = urlConnection.getInputStream();
fileOut = new FileOutputStream(outputFile);
while ((i = response.read()) != -1) {
fileOut.write(i);
}
fileOut.close();
谢谢!
推荐阅读
- php - 将准备好的语句结果存储到 json 数组中的问题
- angular - 在 Asp.net core 2.2.1 中访问 XMLHttpRequest
- docker - 从没有网络服务器的 docker 容器中提供静态文件,由 nginx 反向代理指向
- python - 初始化和验证表单后更改 BoundField 值
- javascript - 使用 :hidden 选择器删除隐藏元素
- python-3.x - 如何在程序结束时关闭python进程
- spring - 使用 Hibernate JPA 处理工作单元的问题
- sockets - 带有raspberrypi的android设备的蓝牙通信-连接被拒绝时出现错误
- c - 子进程和父进程之间的同步 c
- typescript - Typescript 中的字符串验证