2
這就是我遇到的問題。HttpUrlConnection getResponseCode引發java.net.SocketException:意外的服務器文件結尾
/**
* Perform a post while retrieving an object in return.
* @param urlPath path to requested resource
* @param obj object to post
* @return object retrieved from server
*/
private Object doPostGet(String urlPath, Object obj) {
try {
URL url = new URL("http://" + this.host + ":" + this.port + urlPath);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "text/xml");
con.setRequestProperty("Accept", "text/plain");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
xStream.toXML(obj, con.getOutputStream());
con.getOutputStream().close();
Object outObj = null;
if (con.getResponseCode() == Handler.OK) {
InputStream in = new BufferedInputStream(con.getInputStream());
assert in != null;
outObj = xStream.fromXML(in);
in.close();
} else if (con.getResponseCode() == Handler.FAILED_AUTH) {
//
} else if (con.getResponseCode() == Handler.BAD_REQUEST) {
//
}
con.disconnect();
return outObj;
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:718)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:715)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1322)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at mock.communicator.Communicator.doPostGet(Communicator.java:131)
at mock.communicator.Communicator.main(Communicator.java:102)
Communicator的第131行是「if(con.getResponseCode()== Handler.OK){」。我不確定是什麼原因造成的,我對這個東西有點新鮮,所以我的理解是有限的。如果你能幫助我理解我做錯了什麼,那會很好。如果你需要任何服務器端代碼讓我知道,我使用HttpHandlers運行我自己的HttpServer。
這是一個服務器端問題。它如何響應? –
你說得對,服務器壞了,但並沒有拋出任何異常的例外。我認爲這可能與發生的雙重POST有關。每當我做一個POST時,都會因爲某種原因發送兩次,而不是一次。你能看到有什麼證據表明會造成這種情況嗎? – CamHart
不是。逐行調試並檢查。 –