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();
	}

}


   

相关文章:

  • 2021-07-05
  • 2022-01-06
  • 2022-02-09
  • 2021-06-11
  • 2021-11-13
  • 2021-11-12
  • 2021-11-30
猜你喜欢
  • 2022-01-15
  • 2021-09-04
  • 2021-08-19
  • 2021-11-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案