HTTP基本协议(查看网页代码)
此示例已实现查看网页的代码来理解HTTP基本协议:
(返回的是百度首页的网页代码)
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.OutputStream; 5 import java.io.OutputStreamWriter; 6 import java.io.PrintWriter; 7 import java.net.Socket; 8 9 10 public class HttpTest { 11 12 /** 13 * @param args 14 */ 15 public static void main(String[] args) throws Exception{ 16 // TODO Auto-generated method stub 17 Socket s=new Socket("202.108.22.5",80); 18 PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream())); 19 pw.println("GET / HTTP/1.1"); 20 pw.println("Host:www.baidu.com"); 21 pw.println("Context-Type:text/html"); 22 pw.println(); 23 pw.flush(); 24 BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); 25 String str=""; 26 while((str=br.readLine())!=null) 27 { 28 System.out.println(str); 29 } 30 br.close(); 31 pw.close(); 32 s.close(); 33 } 34 35 }