HttpConnection 基於 Socket 手工實現 HTTP/1.0 協議,提供比 java.net.URLConnection 更精細的控制,尤其在 POST 表單提交、請求頭自定義、流式響應處理方面更靈活。
setUsePost(boolean)addGet(name, value) / addPost(name, value) 自動 URL 編碼並拼接setRequestProperty(name, value),連接前有效setUseCaches(false) 自動添加 Pragma: no-cachegetInputStream() 獲取原始輸入流getByteArray() 一次性讀取所有字節getContentType() / getContentLength() 解析響應頭public void connect() throws IOException {
// 解析 URL、創建 Socket、發送請求行、請求頭、POST 體
// 自動處理 Content-Length、Content-Type
}
private void startInput() throws IOException {
DataInputStream din = new DataInputStream(socket.getInputStream());
String line = din.readLine(); // 忽略狀態行
while ((line = din.readLine()) != null && line.length() > 0) {
int idx = line.indexOf(": ");
if (idx > 0) {
resHeaderNames.add(line.substring(0, idx).toLowerCase());
resHeaderValues.add(line.substring(idx + 2));
}
}
inputStarted = true;
}
URL url = new URL("http", "192.168.0.3", "/Post.PHP");
HttpConnection con = new HttpConnection(url);
con.setUsePost(true);
con.setUseCaches(false);
con.addGet("TextField", "你好");
con.addGet("Submit", "submit");
con.connect();
byte[] ret = con.getByteArray();
System.out.println(new String(ret));
URL url = new URL("http", "192.168.0.3", "/codemaker/IMAGES/BO.GIF");
HttpConnection con = new HttpConnection(url);
con.connect();
FileOutputStream fos = new FileOutputStream("d:\\bo.gif");
fos.write(con.getByteArray());
fos.close();
雖然標準庫 HttpURLConnection 或 Apache HttpClient 更健壯,但此實現展示了 HTTP 協議的核心機制,適合深入理解網絡編程原理。