将响应发送到HttpURLConnection.getInputStream()并避免“无效的Http响应”的格式是什么?

时间:2018-06-30 16:29:19

标签: java http

我的服务器通过以下方式向HTTPUrlConnection发送响应:

ServerSocket servSok = new ServerSocket(portNmb);
Socket sok = servSok.accept();
processTheIncomingData(sok.getInputStream());
Writer wrtr = new OutputStreamWriter(sok.getOutputStream());
wrtr.write("<html><body>123 Hello World</body></html>"); // <------- format?
wrtr.flush();

客户

HttpURLConnection conn = (HttpUTLConnection) url.openConnection();    
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
sendSomeData(conn.getOutputStream());
String mssg = conn.getResponseMessage(); // <----- Invalid Http Response

conn.getResponseCode()还给出了相同的“ 无效的http响应”。

1 个答案:

答案 0 :(得分:-1)

我同意@JBNizet。 HTTP是一个非常复杂的协议。您应该使用服务器。

但是,如果您是为一个玩具项目编写的,那么这里有一些代码可以帮助您入门。 请勿在生产中使用任何此类内容:)

    String content = "<html><body>123 Hello World</body></html>";
    Writer wrtr = new OutputStreamWriter(sok.getOutputStream());
    wrtr.write("HTTP/1.1 200 OK\n");
    wrtr.write("Content-Type: text/html; charset=UTF-8\n");
    //assuming content is pure ascii
    wrtr.write("Content-Length: " + content.length() + "\n");
    wrtr.write("Connection: close\n\n");
    wrtr.write(content);
    wrtr.flush();
    //then close the connection, do not reuse the connection
    //as you might not have consumed the full request content