FileNotFoundException异常与有效网址404个状态上的HTTP GET请求(Fil

2019-07-29 20:02发布

我有以下的代码来执行以下网址的GET请求:

http://rt.hnnnglmbrg.de/server.php/someReferenceNumber

然而,这里是我的logcat输出:

java.io.FileNotFoundException: http://rt.hnnnglmbrg.de/server.php/6

为什么它返回404当URL显然是有效的?

这里是我的连接代码:

/**
 * Performs an HTTP GET request that returns base64 data from the server
 * 
 * @param ref
 *            The Accident's reference
 * @return The base64 data from the server.
 */
public static String performGet(String ref) {
    String returnRef = null;
    try {
        URL url = new URL(SERVER_URL + "/" + ref);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");

        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        returnRef = builder.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return returnRef;
}

Answer 1:

当你请求的URL,它实际上返回HTTP代码404 ,意为没有找到。 如果你有控制权交给PHP脚本,标题设置为200 ,表示文件中找到。



Answer 2:

你得到一个404 ,如上说。 为了避免异常,尝试这样的事情:

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect () ; 
int code = con.getResponseCode() ;
if (code == HttpURLConnection.HTTP_NOT_FOUND)
{
    // Handle error
}
else
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

    // etc...
}


Answer 3:

永远不要相信你在浏览器中看到。 总是试图模仿使用类似卷曲你的要求,你会清楚地看到,你得到一个HTTP 404响应代码。

java.net将HTTP 404代码转换为一个FileNotFoundException异常

curl -v  http://rt.hnnnglmbrg.de/server.php/4
* About to connect() to rt.hnnnglmbrg.de port 80 (#0)
*   Trying 217.160.115.112... connected
* Connected to rt.hnnnglmbrg.de (217.160.115.112) port 80 (#0)
> GET /server.php/4 HTTP/1.1
> User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5
> Host: rt.hnnnglmbrg.de
> Accept: */*
> 
< HTTP/1.1 404 Not Found
< Date: Mon, 11 Jun 2012 07:34:55 GMT
< Server: Apache
< X-Powered-By: PHP/5.2.17
< Transfer-Encoding: chunked
< Content-Type: text/html
< 
* Connection #0 to host rt.hnnnglmbrg.de left intact
* Closing connection #0
0

从的Javadoc http://docs.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html

返回错误流如果连接失败但服务器仍然发送了有用的数据。 典型的例子是,当HTTP服务器使用404,这将导致一个FileNotFoundException异常在连接抛出响应,但服务器与建议发送的HTML帮助页面,以什么做的。



文章来源: FileNotFoundException with 404 status for valid URL on HTTP GET request