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

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

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

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

}

 

posted @ 2016-01-29 17:26  亦真亦假,何必当真  阅读(965)  评论(0编辑  收藏  举报