【问题标题】:java.io.IOException: Server returned HTTP response code: 400 for URLjava.io.IOException:服务器返回 HTTP 响应代码:URL 为 400
【发布时间】: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


【解决方案1】:

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

基本上,您发送到服务器的内容无效或未按预期方式格式化。这可能是由于用户代理、安全等原因。我对相关网站的了解不够,无法告诉您他们的期望,您可能想查看该网站以获取有关 API 的任何信息,或者您可以使用的类似信息.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多