import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; public class HttpDemo { /** * 使用Socket抓取网页源代码 */ public static void main(String[] args) throws IOException { //想要抓取的网页主机名 //域名www.baidu.com,旗下有好多主机,比如tieba.baidu.com,map.baidu.com String host = "map.baidu.com"; //依据主机名获取ip地址 InetAddress ip = InetAddress.getByName(host); //建立连接 Socket s = new Socket(ip,80); //向server端写入http协议请求 PrintWriter pw = new PrintWriter(s.getOutputStream()); // "/"请求根页面 pw.println("GET / HTTP/1.1"); pw.println("Host: "+host); pw.println("Content-Type: text/html"); pw.println(); pw.flush(); //将获取到的页面输出在控制台 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = ""; while((str=br.readLine())!=null){ System.out.println(str); } br.close(); pw.close(); s.close(); } }