【问题标题】:Response from HttpURLConnection different from curl response来自 HttpURLConnection 的响应与 curl 响应不同
【发布时间】:2013-10-27 00:00:30
【问题描述】:

我试图从 HttpURLConnection 获得响应,但它抛出 java.io.FileNotFoundException。

HttpURLConnection:

/**
* Call URL using HttpURLConnection
*
* @param url - the URL to be called
**/
public static String getHUCResponse(String url) throws IOException {

    InputStream inps = null;
    String res = "";
    try {

        URL getURL = new URL(url);

        HttpURLConnection huc =  ( HttpURLConnection )  getURL.openConnection ();
        huc.setConnectTimeout(60000); // 1 minute
        huc.setReadTimeout(60000); // 1 minute

        huc.setRequestMethod("GET");

        inps = huc.getInputStream(); // throws java.io.FileNotFoundException
        res = IOUtils.toString(inps,"UTF8");
    } 
    catch (IOException except){
        throw except;
    }       
    finally {
        IOUtils.closeQuietly(inps);
    }

    return res;
}

错误跟踪:

    java.io.FileNotFoundException: url
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
        at HttpUtils.getHUCResponse(HttpUtils.java:440)

卷曲:

    $ curl url
    user not found

    $ curl -I url
    HTTP/1.1 404 Not Found
    Server: nginx/1.4.2
    Date: Sat, 26 Oct 2013 23:45:20 GMT
    Content-Length: 14
    Connection: keep-alive

我希望得到“未找到用户”作为 HttpURLConnection 的响应,因为这是返回 404 错误的内容。

我可能会错过什么?

谢谢。

【问题讨论】:

    标签: java curl httpurlconnection urlconnection


    【解决方案1】:

    当错误代码为 400 或更高时,您将获得带有 getErrorStream 而不是 getInputStream 的响应的输入流(是的,我知道,有人认为这是个好主意)。

    当您调用 getInputStream 但代码为 400 或更高时,我想我记得在这种情况下得到 null 但它似乎让您收到 FileNotFoundException,您只需要添加对 getResponseCode() 的检查并使用正确的获取流的方法。

    【讨论】:

    • 我添加了错误跟踪。调用 getErrorStream 意味着添加对响应代码的检查。在 Java 中有没有一种方法可以得到 curl 返回的响应,无论返回码是什么? IOUtils 来自不同的 apache 包,但这不是问题的原因。
    • 可能是因为您告诉它处理实际上为空的输入流... curl 是一个命令行工具,它与您在 java 中所做的事情无关。您可以在 java 中使用许多库,这是关于 HttpURLConnection 的,在这种情况下不,响应将在 getErrorStream 或 getInputStream 中,具体取决于状态代码以及响应中是否实际存在正文。
    • 错误不是来自 IOUtils。即使我删除 IOUtils 上的行,它也会被抛出。但你在 getErrorStream 上是对的。我可能需要使用与 HttpURLConnection 不同的东西(其行为方式与 curl 相似)。
    【解决方案2】:

    我,Java 做得很好。 404 http 代码等于FileNotFoundExceptionuser not found 是一个奇怪的错误消息,你永远不会从 HttpURLConnection 看到它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 2014-01-21
      相关资源
      最近更新 更多