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.
I had the same issue. I wanted to send data via POST. I used the following code:
I used Jsoup for parse:
i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.
Method Call
Utility Class
Try this pattern:
I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.
That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!
I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:
This answer covers the specific case of the POST Call using a Custom Java POJO.
Using maven dependency for Gson to serialize our Java Object to JSON.
Install Gson using the dependency below.
For those using gradle can use the below
Other imports used:
Now, we can go ahead and use the HttpPost provided by Apache
The above code will return with the response code received from the POST Call