我正在尝试使用套接字从Java客户端发布一些数据。它与运行php代码的本地主机通信,这些本地主机只是简单地输出发送给它的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")作为响应。但它不会将post参数传递给服务器。下面是输出:
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 )仅供参考,此设置适用于GET请求。
知道这是怎么回事吗?
发布于 2011-08-26 05:05:34
正如Jochen和chesles正确地指出的那样,您使用了错误的Content-Type:头--它实际上应该是application/x-www-form-urlencoded。然而,还有其他几个问题……
\r\n),在你的代码中它只是一个新的行(\n)。这是一个彻底的协议冲突,我有点惊讶你没有从服务器得到一个400 Bad Request,尽管Apache在这方面可以相当宽宏大量。Connection: close来确保你不会被打开的套接字闲逛,服务器会在请求是不需要的时候立即关闭连接。PHP足够智能,可以自己解决这个问题,但其他服务器语言和实现可能无法做到……如果您正在使用任何处于原始状态的标准化协议,那么您应该始终至少从扫描the RFC开始。
另外,请学习secure your Apache installs...
发布于 2011-08-26 04:50:44
看起来您正在尝试以application/x-www-form-urlencoded格式发送数据,但是您正在将Content-Type设置为text/html。
发布于 2011-08-26 05:02:58
使用
out.write("Content-Type: application/x-www-form-urlencoded\n\n");而不是。正如this page所说:
Content-Length和Content-Type标头非常重要,因为它们告诉web服务器需要多少字节的数据,以及由MIME类型标识的数据类型。
使用application/x-www-form-urlencoded发送表单数据,即key=value&key2=value2格式的数据。value是否包含HTML或其他数据并不重要;服务器将为您解释这些数据,您将能够像往常一样在PHP端的$_POST或$_REQUEST数组中检索数据。
或者,您可以使用适当的Content-Type标头以原始HTML、XML等格式发送数据,但随后必须通过读取特殊文件php://input来retrieve the data manually in PHP
<?php
echo file_get_contents("php://input");
?>顺便说一句,如果您要将其用于任何足够复杂的事情,我强烈建议使用HTTPClient这样的HTTP客户端库。
https://stackoverflow.com/questions/7196749
复制相似问题