用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 }