代码如下
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class HttpConnection
{
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException
{
String ip = “127.0.0.1″ ;
int port = 80 ;
Socket soc = new Socket(ip, port);
System.out.println(“———————————-”);
System.out.println(“\n\n\n\n”);
BufferedReader in = new BufferedReader( new InputStreamReader(soc.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
StringBuffer meth = new StringBuffer();
meth.append(“GET / HTTP/1.1\r\n”);
// meth.append(“accept:*/*\r\n”);
meth.append(“host:127.0.0.1\r\n”);
meth.append(“”);
meth.append(“”);
out.write(meth.toString());
out.write(“\r\n”);
out.flush();
String line = null ;
while( (line = in.readLine())!= null)
{
System.out.println(line);
}
}
}
输出
———————————-
HTTP/1.1 200 OK
Date: Tue, 06 Mar 2012 12:32:58 GMT
Server: Apache/2.2.22 (Win32)
Last-Modified: Tue, 06 Mar 2012 11:46:06 GMT
ETag: “b000000008d9e-57-4ba9196947acd”
Accept-Ranges: bytes
Content-Length: 87
Content-Type: text/html
Here is body!
终于看到了期待已久的HTTP/1.1 200 OK 。