POST请求返回URL的FileNotFoundException
在安卓系统中,我向https://nitos.gr Url发起了一个Http POST请求。
该url没有域名。因为Stackoverflow不允许在文本中包含数字URL,所以我只是随机写了一个https://nitos.gr来作为示例。
我收到了一个400响应代码,并输出getErrorStream()得到libcore.net.http.UnknownLengthHttpInputStream@41eba330。
但是,我成功地执行了HTTP GET请求。该url是https,因此我使用了一个虚假的信任管理器允许所有SSL连接。
总之:
协议:HTTPS
GET请求:成功
POST请求:失败
请求代码:400
错误消息:java.io.FileNotFoundException: https://nitos.gr
ErrorStream:java.io.FileNotFoundException: https://nitos.gr
执行POST请求的方法如下:
public void setTestbedData(String path, String data) {
HttpURLConnection con = null;
try {
con = (HttpURLConnection) ( new URL(Constants.BASE_URL + path)).openConnection();
// If you invoke the method setDoOutput(true) on the URLConnection, it will always use the POST method.
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
Log.i("data", data);
OutputStream outputStream = con.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
Log.w("RESPONSE CODE", "code " + con.getResponseCode());
Log.w("this is connection ",""+con);
InputStream errorstream = con.getErrorStream();
Log.w("GetErrorStream ", ""+errorstream);
InputStream _is;
if (con.getResponseCode() >= 400) {
_is = con.getInputStream();
} else {
_is = con.getErrorStream();
String result = getStringFromInputStream(_is);
Log.i("Error != 400", result);
}
if (con.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ con.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
Log.i("TestbedHttpClient","Output from Server:");
while ((output = responseBuffer.readLine()) != null) {
Log.i("Output",output);
}
con.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
错误信息:
响应代码(18936):代码 400 libcore.net.http.HttpsURLConnectionImpl$HttpUrlConnectionDelegate:https://nitos.gr GetErrorStream(18936):libcore.net.http.UnknownLengthHttpInputStream@41eba330 System.err(18936):java.io.FileNotFoundException:https://nitos.gr System.err(18936):在libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)。
BufferedReader
)相同的方式处理它。然后您将看到服务器的响应。这只是更进一步了解您所犯的错误的微小一步... - hgoebl