用Java Socket 封装的HTTP 请求
1 package com.test.socket;
2
3 import java.io.*;
4 import java.net.*;
5
6 public class HTTPSocket
7 {
8 public static void main(String[ ] args) throws UnknownHostException, IOException
9 {
10 String host = "127.0.0.1";
11 int port = 8888;
12 Socket socket = new Socket(host, port);
13
14 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
15 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
16
17 StringBuffer sb = new StringBuffer();
18 //请求的连接地址
19 sb.append("POST /ServletBindUrl HTTP/1.1\r\n")
20 .append("Host:"+ host + "\r\n")
21 .append("Content-Type:application/x-www-form-urlencoded\r\n")
22 .append("Content-Length:11\r\n") //11 这个数值是看底下内容的长度的 即多少个字符
23 .append("\r\n")
24 .append("id=01234567\r\n"); //内容
25
26 out.write(sb.toString());
27 out.flush();
28
29 //打印响应
30 String line = "";
31 while((line = in.readLine()) != null)
32 System.out.println(line);
33 }
34 }