【发布时间】:2017-04-25 22:26:25
【问题描述】:
我想从 URL 下载 CSV 文件。为此,我正在使用 HTTP URL 连接。 运行代码时,出现以下错误:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://twc.centercode.com/files/report.aspx/PLS Tracker.csv?t=GetElementFullCSV&r=0668821a036046ef9fde587c609e2c8f&e=47437d179bce477f936dcfdc470bf378
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
请查看以下代码:
final int BUFFER_SIZE = 4096;
String fileURL = "https://twc.centercode.com/files/report.aspx/PLS Tracker.csv?t=GetElementFullCSV&r=0668821a036046ef9fde587c609e2c8f&e=47437d179bce477f936dcfdc470bf378";
String fileName = "EFTReportTest.csv";
String saveDir = "D:\\";
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + "" + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
}
else{
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
请让我知道我在这里做错了什么。
【问题讨论】:
-
您的网址可能无法访问,请检查
-
@TuyenNguyen - 当我直接在 Chrome 浏览器上点击 URL 时,它正在下载文件。
-
我也测试过,但是HttpURLConnection不能通过异常打开这个URL给它。您应该检查与 HttpURLConnection 一起使用的正确 URL 类型
-
还要检查URL的安全性是否有问题,您使用https可能有其他设置?
-
可能服务器会检查 User-Agent、Accept 或任何其他标头。
标签: java http httpurlconnection