我的服务器以这种方式向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响应”。
发布于 2018-07-01 00:48:27
我同意@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
https://stackoverflow.com/questions/51116637
复制相似问题