SOCKET模仿HTTP GET请求

来源:互联网 发布:用c语言计算圆的面积 编辑:程序博客网 时间:2024/06/01 07:52

一、为了更好理解HTTP协议,故用socket模仿http get请求,java代码如下:

package com.ppt.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;import java.net.URL;public class SocketHttpGet {private final String END = "\r\n";private Socket client;private InputStream is;private OutputStream os;private String host;private String path;public SocketHttpGet(String url) {try {init(url);} catch(Exception e) {e.printStackTrace();}}private void init(String url) throws Exception {URL temp = new URL(url);this.host = temp.getHost();this.path = temp.getPath();int port = temp.getDefaultPort();client = new Socket();SocketAddress address = new InetSocketAddress(this.host, port);client.connect(address, 5000);client.setSoTimeout(10000);is = client.getInputStream();os = client.getOutputStream();}public void httpGet() throws IOException {StringBuffer sb = new StringBuffer();sb.append("GET "+ this.path +" HTTP/1.1" + END);sb.append("Host: " + this.host + END);sb.append("User-Agent:Mozilla/4.0(compatible;MSIE6.0;Windows NT 5.0)" + END);sb.append("Accept-Language:zh-cn" + END);sb.append("Accept-Encoding:deflate" + END);sb.append("Accept:*/*" + END);sb.append("Connection:Keep-Alive" + END);sb.append(END);String requestString = sb.toString();System.out.println(requestString);os.write(requestString.getBytes());os.flush();BufferedReader reader = new BufferedReader(new InputStreamReader(is));String result = "";int contentLength = 0;int headLength = 0;while(true) {result=reader.readLine();headLength += result.length();if(result == null || "".equals(result.trim())) {break;}if(result.contains("Content-Length")) {String str = result.substring("Content-Length:".length(), result.length());contentLength = Integer.parseInt(str.trim());}System.out.println(result);}System.out.println("head length is: " + headLength);char[] rBuf = new char[5120];int readLength = 0;StringBuffer sbResult = new StringBuffer();while(readLength < contentLength) {int i = 0;try {i = reader.read(rBuf);} catch(Exception e) {e.printStackTrace();break;}readLength += i;sbResult.append(rBuf);}String str = sbResult.toString();System.out.println(str);}public static void main(String[] args) throws Exception {String url = "http://blog.csdn.net/jnu_simba/article/details/8957242";SocketHttpGet get = new SocketHttpGet(url);get.httpGet();}}


0 0