码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-01-29 21:02:55      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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

}

 

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!