我試圖使用套接字從Java客戶端發佈一些數據。它會與運行php代碼的localhost進行交流,它只是將發送給它的後續參數吐出。Http Post不發佈數據
這裏是Java客戶端:
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8888);
String reqStr = "testString";
String urlParameters = URLEncoder.encode("myparam="+reqStr, "UTF-8");
System.out.println("Params: " + urlParameters);
try {
Writer out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
out.write("POST /post3.php HTTP/1.1\r\n");
out.write("Host: localhost:8888\r\n");
out.write("Content-Length: " + Integer.toString(urlParameters.getBytes().length) + "\r\n");
out.write("Content-Type: text/html\r\n\n");
out.write(urlParameters);
out.write("\r\n");
out.flush();
InputStream inputstream = socket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null) {
System.out.println("Received " + string);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
這是post3.php的樣子:
<?php
$post = $_REQUEST;
echo print_r($post, true);
?>
我希望看到一個數組(myparams => 「的TestString」)作爲響應。但它沒有通過發佈參數到服務器。 這裏輸出:
Received HTTP/1.1 200 OK
Received Date: Thu, 25 Aug 2011 20:25:56 GMT
Received Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6
Received X-Powered-By: PHP/5.3.6
Received Content-Length: 10
Received Content-Type: text/html
Received
Received Array
Received (
Received)
只是一個FYI,這個設置適用於GET請求。
任何想法這裏發生了什麼?
只是想知道...有你不使用任何理由[了HTTPClient](http://hc.apache.org/httpcomponents-client-ga/ index.html的)? – chesles
或[Resty](http://beders.github.com/Resty/Resty/Overview.html)。 –
@ chesles-我正在通過SSL發送數據。 HttpClient-4的文檔對設置定製的SSLSocketFactory並不是很有幫助。所以,在我用頭部計算出用HttpClient4定製SSLSocketFactory之前,我正在試用普通套接字上的東西。 – bianca