2014-10-09 30 views
0

这是我的代码:为什么在使用Java的此TCP连接到stackoverflow后,我得到的主机响应不佳?

public class TestClass { 
    public static void main(String[] args) throws Exception { 
     Socket socket = new Socket("198.252.206.16",80); 
     DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream()); 
     outToServer.writeBytes("GET http://stackoverflow.com:80 HTTP/1.1\n\nHost: http://stackoverflow.com\n"); 
     InputStream inputStream = socket.getInputStream(); 
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
     int x; 
     while((x = inputStreamReader.read()) != -1) { 
      System.out.print((char) x); 
     } 
    } 
} 

而且我得到的回应:

HTTP/1.1 400 Bad Request 
Content-Type: text/html; charset=us-ascii 
Date: Thu, 09 Oct 2014 18:47:26 GMT 
Content-Length: 334 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> 
<HTML><HEAD><TITLE>Bad Request</TITLE> 
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD> 
<BODY><h2>Bad Request - Invalid Hostname</h2> 
<hr><p>HTTP Error 400. The request hostname is invalid.</p> 
</BODY></HTML> 
HTTP/1.0 400 Bad request 
Cache-Control: no-cache 
Connection: close 
Content-Type: text/html 

<html><body><h1>400 Bad request</h1> 
Your browser sent an invalid request. 
</body></html> 

它是什么,我做错了什么?

回答

1

您正在发送Host标头作为GET请求正文的一部分。

outToServer.writeBytes("GET http://stackoverflow.com:80 HTTP/1.1\n\nHost: http://stackoverflow.com\n"); 
//                ^notice two new lines 

所以你的GET就像

GET http://stackoverflow.com:80 HTTP/1.1 // << request method and headers 

Host: http://stackoverflow.com // << request body 

相反,只放有一个新的生产线,以及两个末

outToServer.writeBytes("GET http://stackoverflow.com:80 HTTP/1.1\nHost: http://stackoverflow.com\n\n"); 

这将是正确的像

GET http://stackoverflow.com:80 HTTP/1.1 // << request method and headers 
Host: http://stackoverflow.com 
+0

像往常一样完美.. – 2014-10-09 19:00:15

相关问题