0

I have some connection to url:

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

How I can send post parameter to this url that php function: http://www.php.net/manual/en/reserved.variables.request.php can read it ? I try to according this question: Java - sending HTTP parameters via POST method easily but with no success. It just display empty array

php code:

print_r($_REQUEST,1)

java code:

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();
Community
  • 1
  • 1
hudi
  • 15,555
  • 47
  • 142
  • 246

1 Answers1

0

You forgot to set the Content-Type header, and you need to write the category_name and complete values as a string to the stream.

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();

As you can see, he sets the headers (Content-Type, Charset and Content-Length) and then writes the POST data to the stream. The POST data is just like the GET format: key-value pairs seperated by &, and the key and value are seperated by =.

As the Content-Type is set to www-form-urlencoded, you need to 'url encode' the key and value values. You can do this using the URLEncoder.encode method.

The urlParameters for your POST data would be:

String urlParameters = "category_name=" + URLEncoder.encode(categoryName) + "&complete=" + URLEncoder.encode(complete);
Community
  • 1
  • 1
Diamondo25
  • 769
  • 1
  • 8
  • 21