2017-04-25 727 views
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(); 

请让我知道我在做什么错在这里。

+0

您的网址可能无法访问,请检查它 –

+0

@TuyenNguyen - 当我在Chrome浏览器上直接点击URL时,它正在下载文件。 – Nikhil

+0

我也测试过了,但是HttpURLConnection无法通过这个异常打开这个URL。您应该检查使用HttpURLConnection的正确类型的URL –

回答

0

HTML代码400是“错误的请求” (See here)

基本上,你发送给服务器是无效的或它的预期的方式未格式化。这可能是由于用户代理,安全等原因造成的。我对有关网站的了解不足,无法告诉您他们期望如何,您可能需要查看网站以获取关于API的任何信息,或者可以使用。

相关问题