0
我想从URL下载CSV文件。为此,我使用HTTP URL连接。 运行代码时,我得到以下错误:java.io.IOException:服务器返回的HTTP响应代码:400为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时,它正在下载文件。 – Nikhil
我也测试过了,但是HttpURLConnection无法通过这个异常打开这个URL。您应该检查使用HttpURLConnection的正确类型的URL –