[java] Java - sending HTTP parameters via POST method easily

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&param2=b&param3=c";
    URL url = new URL(request); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
    connection.setRequestProperty("Content-Type", "text/plain"); 
    connection.setRequestProperty("charset", "utf-8");

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




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.

This question is related to java http post httpurlconnection

The answer is

In a GET request, the parameters are sent as part of the URL.

In a POST request, the parameters are sent as a body of the request, after the headers.

To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

This code should get you started:

String urlParameters  = "param1=a&param2=b&param3=c";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
String request        = "http://example.com/index.php";
URL    url            = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );

Similar questions with java tag:

Similar questions with http tag:

Similar questions with post tag:

Similar questions with httpurlconnection tag: