I am successfully using this code to send HTTP
requests with some parameters via GET
method
void sendRequest(String request)
{
// i.e.: request = "http://example.com/index.php?param1=a¶m2=b¶m3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
}
Now I may need to send the parameters (i.e. param1, param2, param3) via POST
method because they are very long.
I was thinking to add an extra parameter to that method (i.e. String httpMethod).
How can I change the code above as little as possible to be able to send paramters either via GET
or POST
?
I was hoping that changing
connection.setRequestMethod("GET");
to
connection.setRequestMethod("POST");
would have done the trick, but the parameters are still sent via GET method.
Has HttpURLConnection
got any method that would help?
Is there any helpful Java construct?
Any help would be very much appreciated.
GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.
Hello pls use this class to improve your post method
I higly recomend http-request built on apache http api.
For your case you can see example:
If you are not interested in the response body
For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java
Appears that you also have to call
connection.getOutputStream()
"at least once" (as well assetDoOutput(true)
) for it to treat it as a POST.So the minimum required code is:
You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.
You can also use NameValuePair apparently.