纯手工打造HTTP请求,淫领HTTP协议!~
public static void main(String[] args) throws Exception{// 我要模拟的URL//http://domain.oray.com/domain/check.php?domain=ixr.name&free=0String host = "domain.oray.com";// 解析域名IPString ip = InetAddress.getByName(host).getHostAddress();// 建立socket连接Socket socket = new Socket(ip,80); PrintWriter print = new PrintWriter(socket.getOutputStream()); // 根据 HTTP协议输入请求协议print.println(String.format("GET /domain/check.php?domain=%s&free=0 HTTP/1.1", "ixr.name"));// 告诉服务器我们请求的 HOSTprint.println(String.format("Host: %s",host));// 嘻嘻,挑战下GIZP的HTML解析,告诉服务器我是支持GZIP的print.println("Accept-Encoding: gzip, deflate");// 我们骗下我们是火星浏览器,没错我们是火星浏览器1.擦 版本 系统是 火星 操作系统 1.擦 版本。print.println("User-AgentMars/1.x (Mars OS 1.x)");// HTTP 是说 一个空行结束头信息 print.println(); // 提交下才有用哟!~ print.flush(); // 接下来我们获取服务器的返回流 InputStream inputStream = socket.getInputStream(); // 把流读取到一个字节流里 方便循环操作吧!~ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; // 这里就读了 for(int idx = inputStream.read(bytes);;idx = inputStream.read(bytes)){ byteArrayOutputStream.write(bytes,0,idx); if(idx < 1024){ break; } } // 既然保存过就把SOCKET关闭吧!~ // 不然服务器要哭泣的,别人的服务器我们伤不起!~ socket.close(); // 放在一个字节数组里,更加的方便操作!~ bytes = byteArrayOutputStream.toByteArray(); // 关闭这个流,因为字节读取出来了!~ byteArrayOutputStream.close(); // 这个记录head的结束位置,后边的记录上一行的结束位置。 int head_end = -1,index = 0; for (int idx = 0; idx < bytes.length - 4; idx++) { byte ln11 = bytes[idx + 0]; byte ln12 = bytes[idx + 1]; byte ln21 = bytes[idx + 2]; byte ln22 = bytes[idx + 3]; // 这里如果 说明下 字节 13 12 代表 \r\n 如果遇到 这个 就说明一个问题,一行信息结束(嘻嘻)!~ if(ln11 == 13 && ln12 == 10){ // 我们打印头信息看看 System.out.println(new String(bytes,index,idx - index)); // + 2 是把上一行的 \r\n符跳过!~ index = idx + 2; } // 如果遇到 \r\n\r\n 那么头就结束了。 if(ln11 == 13 && ln12 == 10 && ln21 == 13 && ln22 == 10){ // 这个8很有意义的,4代表的是 \r\n\r\n // 后边4个代表的是 2个数字(这个数字我也不知道什么意思,有的网页是3个有的木有),在加上这一行的 \r\n head_end = idx + 8; // 头信息完了,后边的内容是GZIP压缩的流了 在读取小心爆菊花!~ break; } } // 算出位置把字节转换成一个InputStream ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes, head_end, bytes.length - head_end); // 使用GZIP流包装下,这样就可以解压了 GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream); // 在使用Reader包装下方便我们读 BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream)); // 因为内容就一行直接 readLine 把!~ 嘻嘻,如果很多行你就 使用 for 读到结尾好了!~ String resultJson = reader.readLine(); // 打印下 System.out.println(resultJson); // 这个可以关闭了 reader.close(); }
?
打印信息贴上
HTTP/1.1 200 OK
Server: nginx/0.8.15
Date: Thu, 26 May 2011 04:08:19 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Set-Cookie: _s_id_=i62268mltg0iu5g65s64bdeps6; path=/; domain=oray.com
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Encoding: gzip
[{"domain":"ixr.name","ret":0}]