如何发送可以通过php读取的post参数

时间:2014-03-04 13:47:46

标签: java php

我与url有一些联系:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

如何将post参数发送到这个url php函数:http://www.php.net/manual/en/reserved.variables.request.php可以读取它?我试着回答这个问题:Java - sending HTTP parameters via POST method easily但没有成功。它只显示空数组

php代码:

print_r($_REQUEST,1)

java代码:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("category_name", categoryName);
connection.setRequestProperty("complete", complete);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
connection.getResponseCode();

wr.flush();
wr.close();
connection.disconnect();

1 个答案:

答案 0 :(得分:0)

您忘记设置Content-Type标头,并且需要将category_namecomplete值作为字符串写入流中。

Quoting the code from the post you mentioned:

String urlParameters = "param1=a&param2=b&param3=c";
String request = "http://example.com/index.php";
URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();

如您所见,他设置标题(Content-Type,Charset和Content-Length),然后将POST数据写入流。 POST数据与GET格式类似:由&分隔的键值对,键和值由=分隔。

由于Content-Type设置为www-form-urlencoded,您需要'url encode'键值和值。您可以使用URLEncoder.encode方法执行此操作。

您的POST数据的urlParameters将是:

String urlParameters = "category_name=" + URLEncoder.encode(categoryName) + "&complete=" + URLEncoder.encode(complete);