通过socket实现http通讯代码理解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过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); }
以上是关于通过socket实现http通讯代码理解的主要内容,如果未能解决你的问题,请参考以下文章