【发布时间】:2012-05-27 06:29:56
【问题描述】:
当我通过套接字发送正常的 HTTP 请求时,服务器没有以 OK 响应进行响应。我从 Firefox 复制了 HTTP 标头。代码如下:
Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.print("GET / HTTP/1.1");
pw.print("Host: stackoverflow.com");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String t;
while((t = br.readLine()) != null) System.out.println(t);
br.close();
但是,这是我收到的回复:
HTTP/1.0 408 Request Time-out
Cache-Control: no-cache
Connection: close
Content-Type: text/html
<html><body><h1>408 Request Time-out</h1>
Your browser didn't send a complete request in time.
</body></html>
我知道使用URL.openStream()可以做到这一点,但是为什么我手动发送HTTP请求时服务器无法识别?
【问题讨论】:
-
我认为您必须在所有标题之后发送一个额外的换行符;
pw.println();,并使用println()作为标题? -
@Torious 是的,这就是问题所在。谢谢:)
-
对于 HTTP,换行符的格式必须为 \r\n。
-
好吧,当我尝试你的代码时它不会打印任何东西。
标签: java http sockets network-programming http-headers