Import java.net.*;
Import java.io.*;
public class HTTPClient {
String host= "www.baidu.com";
int port=80;
Socket socket;
public void Createsocket () throws exception{
Socket=new Socket ("www.baidu.com", 80);
}
public void Communicate () throws exception{
SYSTEM.OUT.PRINTLN ("---");
StringBuffer sb=new stringbuffer ("GET" + "/" + "http/1.1\r\n");
Sb.append ("host:www.baidu.com\r\n");
Sb.append ("Accept: */*\r\n");
Sb.append ("accept-language:zh-cn\r\n");
Sb.append ("Accept-encoding:gzip, deflate\r\n");
Sb.append ("user-agent:mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0) \ r \ n ");
Sb.append ("connection:keep-alive\r\n\r\n");
Make an HTTP request
OutputStream Socketout=socket.getoutputstream ();
Socketout.write (Sb.tostring (). GetBytes ());
Socket.shutdownoutput (); Turn off the output stream
Receive response results
/* InputStream socketin=socket.getinputstream ();
Bytearrayoutputstream buffer=new Bytearrayoutputstream ();
Byte[] Buff=new byte[1024];
int len=-1;
while ((Len=socketin.read (Buff))!=-1) {
Buffer.write (Buff,0,len);
}
System.out.println (New String (Buffer.tobytearray ())); Convert a byte array to a string
*/
InputStream Socketin=socket.getinputstream ();
BufferedReader br=new BufferedReader (New InputStreamReader (Socketin));
String data;
while ((Data=br.readline ())!=null) {
SYSTEM.OUT.PRINTLN (data);
}
Socket.close ();
}
public static void Main (String args[]) throws exception{
HTTPClient client=new HTTPClient ();
Client.createsocket ();
Client.communicate ();
}
}
Chapter One Introduction to Java Network programming _httpclient.java