0

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

HttpURL 连接:

/**
* 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 错误的内容。

我会错过什么?

谢谢。

4

2 回答 2

2

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

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

于 2013-10-27T00:43:51.183 回答
0

是的,Java 做得很好。404 http 代码等于FileNotFoundException. user not found是您永远不会看到的奇怪错误消息HttpURLConnection

于 2013-10-27T01:19:23.830 回答