通过socket实现http通讯代码理解

1、首先构造http协议报头:

String dd = "GET http://www.baidu.com HTTP/1.1" +
        "
" +
        "Host: www.baidu.com" +
        "
" +
        "User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:23.0) Gecko/20100101 Firefox/23.0" +
        "
" +
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" +
        "
" +
        "Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3" +
        "
" +
        "Accept-Encoding: gzip, deflate" +
        "
" +
        "Connection: keep-alive" +
        "
" +
        "
";

2、使用socket发送请求:

Socket socket = new Socket(InetAddress.getByName("www.baidu.com"),80);
OutputStream os = socket.getOutputStream();
os.write(dd.getBytes());
os.flush();

3、接受服务端返回的数据:

InputStream is = socket.getInputStream();
int count = 0;
byte[] b = new byte[1024];
while((count = is.read(b))!=-1){

String ss = new String(b,0,count,"UTF-8");
System.out.print(ss);

}
原文地址:https://www.cnblogs.com/wbjgogogo/p/5169652.html