http 请求报文和响应报文编写 (java socket实例)

http 请求头由三部分组成:请求行、请求头部、请求体

GET  / HTTP/1.1\r\n              
Host: 114.55.40.20\r\n
Content-Type: text/html;charset=utf8\r\n
Connection: keep-alive\r\n\r\n

请求体数据

 

下面是简单的java代码实例

Socket socket = new Socket("114.55.40.20",80);
		System.out.println(socket.isConnected());
		//发送的http数据
		StringBuilder requestData = new StringBuilder();
		//header
		Map header = new HashMap();
		header.put("Content-Type", "text/html;charset=utf-8");
		header.put("Connection", "keep-alive");
		header.put("Host", "114.55.40.20");
		header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
		//开始构造 GET 后面的请求路径全写
		requestData.append("GET http://114.55.40.20、 HTTP/1.1\r\n");
		for (Entry  headerEntry : header.entrySet()) {
			requestData.append(headerEntry.getKey() + ": " + headerEntry.getValue() + "\r\n");
		}
		//结束请求头要加\r\n
		requestData.append("\r\n");
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write(requestData.toString().getBytes());
		outputStream.flush();
		InputStream inputStream = socket.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] response = new byte[1024];
		int len = -1;
		while((len = inputStream.read(response)) != -1){
			baos.write(response,0,len);
			System.out.println(1);
		}
		socket.close();
		System.out.println("response:");
		System.out.println(new String(baos.toByteArray()));

 

响应报文由三部分组成:响应行、响应头、响应体
 

HTTP/1.1 200 OK\r\n
Content-Type: application/json\r\n\r\n
{"status": 200,'msg': "It is ok"}

 

你可能感兴趣的:(tcp,http,java)