2

我有以下代码对以下 URL 执行 GET 请求:

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

但是,这是我从 Logcat 的输出:

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

当 URL 明显有效时,为什么它返回 404?

这是我的连接代码:

/**
 * 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;
}
4

3 回答 3

4

当您请求 URL 时,它实际上返回的 HTTP 代码404表示未找到。如果您可以控制 PHP 脚本,请将标头设置200为指示文件已找到。

在此处输入图像描述

于 2012-06-11T07:32:22.417 回答
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...
}
于 2012-06-11T07:39:34.040 回答
1

永远不要相信您在浏览器中看到的内容。始终尝试使用 curl 之类的东西来模仿您的请求,您会清楚地看到您收到的是 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

来自http://docs.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html的 javadocs

如果连接失败但服务器仍然发送了有用的数据,则返回错误流。典型的例子是当 HTTP 服务器响应 404 时,这将导致在连接中抛出 FileNotFoundException,但服务器发送了一个 HTML 帮助页面,其中包含有关如何操作的建议。

于 2012-06-11T07:37:50.287 回答