Java Http~URLConnection响应代码-1

时间:2013-12-06 20:27:24

标签: java nginx httpurlconnection

尝试从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在浏览器中有效。完全相同的代码可以从同一台服务器和目录下载不同的文件......

2 个答案:

答案 0 :(得分:0)

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

  

如果无法从响应中识别出代码,则返回-1(即,   响应无效HTTP)。

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

答案 1 :(得分:0)

有一次我在使用我自己的HTTP服务器实现时遇到过这种情况。在浏览器中运行时,它可以正常工作,但是使用HttpURLConnection会得到Invalid Http response,响应代码将为-1。

问题是HttpURLConnection严格按照格式

查找标题

HTTP/1.1 200 OK

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

HTTP 200 OK

只要我将版本更改为1.1,就可以了。因此,请使用cURL检查您的回复,如下所示:

curl -v -I URL_HERE

希望它有所帮助!