`
txazo
  • 浏览: 79481 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Socket获取HTTP响应

    博客分类:
  • J2SE
阅读更多
目标网页URL:http://www.baidu.com
public class HttpSender {

	private static byte[] request = null;

	static {
		StringBuffer temp = new StringBuffer();
		temp.append("GET http://www.baidu.com HTTP/1.1\r\n");
		temp.append("Host: 119.75.217.109:80\r\n");
		temp.append("Connection: keep-alive\r\n");
		temp.append("Cache-Control: max-age=0\r\n");
		temp
				.append("User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11\r\n");
		temp
				.append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n");
		temp.append("Accept-Encoding: gzip,deflate,sdch\r\n");
		temp.append("Accept-Language: zh-CN,zh;q=0.8\r\n");
		temp.append("Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n");
		temp.append("\r\n");
		request = temp.toString().getBytes();
	}

	public static void sendHttpRequest() throws Exception {
		Socket socket = new Socket("119.75.217.109", 80);

		OutputStream os = socket.getOutputStream();
		os.write(request);
		os.flush();

		BufferedReader br = new BufferedReader(new InputStreamReader(socket
				.getInputStream()));

		String temp = null;
		while ((temp = br.readLine()) != null) {
			System.out.println(temp);
		}

		br.close();
		os.close();
		socket.close();
	}

	public static void main(String[] args) throws Exception {
		sendHttpRequest();
	}

}

运行后输出服务器响应。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics