我与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();
答案 0 :(得分:0)
您忘记设置Content-Type
标头,并且需要将category_name
和complete
值作为字符串写入流中。
Quoting the code from the post you mentioned:
String urlParameters = "param1=a¶m2=b¶m3=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);