通过套接字手动发送HTTP请求 [英] Send HTTP Request manually via socket
本文介绍了通过套接字手动发送HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我通过套接字发送正常的HTTP请求时,服务器不响应OK响应。我从FireFox复制了HTTP标头。下面是代码:
When I send a normal HTTP request via a socket the server does not respond with an OK response. I copied the HTTP header from FireFox. Here is the code:
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();
但是,这是我收到的回复:
However, here is the response I recieved:
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请求?
I know that I can do this by using URL.openStream()
, but why the server doesn't identify the HTTP Request when I send it manually?
推荐答案
两个东西:
- 您应该使用
println
而不是打印
将您的条目打印为单独的行。 - HTTP请求应以空行结尾( link )。所以添加
pw.println();
- You should use
println
instead ofprint
to print your entries to separate lines. - HTTP request should end in a blank line (link). So add
pw.println("");
这篇关于通过套接字手动发送HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文