来自HttpURLConnection的响应与curl响应不同

时间:2013-10-27 00:00:31

标签: java curl httpurlconnection urlconnection

我正在尝试从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:

    $ 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错误返回的内容。

我能错过什么?

感谢。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

上午,Java正在做事。 404 http代码等于FileNotFoundExceptionuser not found是一个奇怪的错误消息,您将永远不会从HttpURLConnection

看到