我有以下代码在以下网址上执行GET请求:
http://rt.hnnnglmbrg.de/server.php/someReferenceNumber
但是,这是Logcat的输出:
java.io.FileNotFoundException: http://rt.hnnnglmbrg.de/server.php/6
为什么在网址明显有效时会返回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;
}
答案 0 :(得分:4)
当您请求URL时,它实际上返回了代码未找到的HTTP代码404
。如果您可以控制PHP脚本,请将标头设置为200
以指示找到文件。
答案 1 :(得分: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...
}
答案 2 :(得分: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的javadoc
如果连接失败但服务器仍然发送了有用的数据,则返回错误流。典型示例是HTTP服务器以404响应,这将导致在连接中抛出FileNotFoundException,但服务器发送了一个HTML帮助页面,其中包含有关如何操作的建议。