【问题标题】:Java Http~URLConnection response code -1Java Http~URLConnection 响应码 -1
【发布时间】:2015-02-08 20:07:40
【问题描述】:

尝试从 Http 服务器 (nginx) 下载 Java 文件

java 尝试下载的完全相同的链接在浏览器中工作并下载,但 java 响应:

java.io.IOException: <URL WOULD BE HERE> returned response code -1
    at com.atlauncher.data.Downloadable.getConnection(Downloadable.java:149)
    at com.atlauncher.data.Downloadable.getFilesize(Downloadable.java:85)
    at com.atlauncher.workers.InstanceInstaller.configurePack(InstanceInstaller.java:1134)
    at com.atlauncher.workers.InstanceInstaller.doInBackground(InstanceInstaller.java:1399)
    at com.atlauncher.workers.InstanceInstaller.doInBackground(InstanceInstaller.java:59)
    at javax.swing.SwingWorker$1.call(SwingWorker.java:296)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at javax.swing.SwingWorker.run(SwingWorker.java:335)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

下载代码:

this.connection = (HttpURLConnection) new URL(this.url).openConnection();
    this.connection.setUseCaches(false);
    this.connection.setDefaultUseCaches(false);
    this.connection.setConnectTimeout(9000);
    //this.connection.setRequestProperty("Accept-Encoding", "gzip");
    this.connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36");
    this.connection.setRequestProperty("Cache-Control", "no-store,max-age=0,no-cache");
    this.connection.setRequestProperty("Expires", "0");
    this.connection.setRequestProperty("Pragma", "no-cache");
    this.connection.connect();
    if (this.connection.getResponseCode() / 100 != 2) {
        System.out.println(this.connection);
        throw new IOException(this.url + " returned response code "
                + this.connection.getResponseCode());
    }

任何想法为什么会发生这种情况?奇怪的是,完全相同的 url 在浏览器中工作。并且完全相同的代码可以从同一服务器和目录下载不同的文件...

【问题讨论】:

  • 堆栈跟踪不完整,能否提供Caused部分?它只包含Downloadable#getConnection()信息

标签: java nginx httpurlconnection


【解决方案1】:

要找出答案,您不能抛出 IOException 并打印完整的响应。根据getResponseCode()方法的javadoc

如果无法从响应中识别出任何代码(即, 响应不是有效的 HTTP)。

您的响应可能根本不是 HTTP。

【讨论】:

  • 我搜索了很长时间,但在 javadoc 上找不到它! :@ 但经过大约 2 小时的搜索,我设法在某个论坛上找到了其他东西。我不得不禁用keepAlive,并且我还将我的用户代理更改为firefox发送的内容。这似乎工作,扼杀,即使我的服务器不检查那些。 :S
【解决方案2】:

有一次我使用自己的 HTTP 服务器实现时发生过这种情况。在浏览器中运行时,它可以正常工作,但是创建一个 HttpURLConnection 会给出Invalid Http response 并且响应代码将是-1。

问题在于 HttpURLConnection 严格按照格式查找标头

HTTP/1.1 200 OK

但我的自定义服务器只提供了一个

HTTP 200 OK

我将版本更改为 1.1 后,它就可以工作了。因此,请使用 cURL 检查您的响应,如下所示:

curl -v -I URL_HERE

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多