1. 程式人生 > >http 請求報文編寫 (java socket例項)

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<String, String> header = new HashMap<String, String>();
		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<String, String>  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()));