2

这就是我遇到的问题。

    /**
 * 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。

4

1 回答 1

-1

Sotirios Delimanolis 是正确的。服务器未发送响应标头。在我的 HttpHandler 中,我只需要添加这段代码。exchange.sendResponseHeaders(OK, 0);

这解决了这个问题。非常感谢你们!

于 2013-09-03T07:29:23.790 回答