Java - sending HTTP parameters via POST method easily

0 votes

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.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 GETor 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

Jun 7, 2018 in Java by developer_1
• 3,300 points
16,646 views

10 answers to this question.

0 votes

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 );
}
answered Jun 7, 2018 by Rishabh
• 3,540 points
0 votes

Try this it worked fine

import java.net.*;

public class Demo{

  public static void main(){

       String data = "data=Hello+World!";
       URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
       HttpURLConnection con = (HttpURLConnection) url.openConnection();
       con.setRequestMethod("POST");
       con.setDoOutput(true);
       con.getOutputStream().write(data.getBytes("UTF-8"));
       con.getInputStream();

    }

}
answered Dec 10, 2018 by Jhammura
0 votes
    HashMap<String, String> whaturl = new HashMap<String, String>();
    whaturl.put("email","me@abc.com");
    whaturl.put("password","XXXXX");
    String link1 = "http://www.abc.com";
    HttpUtility.newRequest(link1,HttpUtility.METHOD_POST,whaturl, new HttpUtility.Callback() {
        @Override
        public void OnSuccess(String response) {
           System.out.println("Server OnSuccess response="+response);
        }
        @Override
        public void OnError(int status_code, String message) {
              System.out.println("Server OnError status_code="+status_code+" message="+message);
        }
    });
answered Dec 10, 2018 by Shuvodip
0 votes

This can also be a good substitute

public static PricesResponse getResponse(EventRequestRaw request) {
    // String urlParameters  = "param1=a&param2=b&param3=c";
    String urlParameters = Piping.serialize(request);
    HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
    PricesResponse response = null;
    try {
        // POST
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();
        // RESPONSE
        BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
        String json = Buffering.getString(reader);
        response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
        writer.close();
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    conn.disconnect();
    System.out.println("PricesClient: " + response.toString());
    return response;
}
public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
    return RestClient.getConnection(endPoint, "POST", urlParameters);
}
public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
    System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
    HttpURLConnection conn = null;
    try {
        URL url = new URL(endPoint);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/plain");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return conn;
}
answered Dec 10, 2018 by Ritu
0 votes

Use http-request built on apache http api.

answered Dec 10, 2018 by Sukesh
0 votes
public static JSONObject doPostRequest(HashMap<String, String> data, String url) {
    try {
        RequestBody requestBody;
        MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
        if (data != null) {
            for (String key : data.keySet()) {
                String value = data.get(key);
                Utility.printLog("Key Values", key + "-----------------" + value);
                mBuilder.addFormDataPart(key, value);
            }
        } else {
            mBuilder.addFormDataPart("temp", "temp");
        }
        requestBody = mBuilder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        Utility.printLog("URL", url);
        Utility.printLog("Response", responseBody);
        return new JSONObject(responseBody);
    } catch (UnknownHostException | UnsupportedEncodingException e) {
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        e.printStackTrace();
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}
answered Dec 10, 2018 by User57902
0 votes
private static final HttpRequest<?> HTTP_REQUEST = 
     HttpRequestBuilder.createPost("http://example.com/index.php").build();

public void sendRequest(String request){
     ResponseHandler<String> responseHandler = 
           HTTP_REQUEST.executeWithQuery(parameters);
}

Use this function

answered Dec 10, 2018 by Naman
0 votes

Use this function i works fine.

private static final HttpRequest<String.class> HTTPREQUEST = 
      HttpRequestBuilder.createPost("http://abc.com/home.php", String.class)
           .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
           .build();
public void sendRequest(String request){
     String param = request.split("\\?")[1];
     ResponseHandler<String> responseHandler = 
            HTTP_REQUEST.executeWithQuery(parameters);
   System.out.println(responseHandler.getStatusCode());
   System.out.println(responseHandler.get()); //prints response body
}
answered Dec 10, 2018 by Teminnh
0 votes

A very small implementation and it works fine

import java.net.*;
public class Demo{
  public static void main(){
       String link = "data=Hello+World!";
       URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
       HttpURLConnection con = (HttpURLConnection) url.openConnection();
       con.setRequestMethod("POST");
       con.setDoOutput(true);
       con.getOutputStream().write(data.getBytes("UTF-8"));
       con.getInputStream();
    }
}
answered Dec 10, 2018 by findingbugs
0 votes

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.

answered Dec 10, 2018 by robocop

Related Questions In Java

0 votes
2 answers

What is the use of toString method in Java and how can I use it ?

Whenever you require to explore the constructor ...READ MORE

answered Aug 23, 2018 in Java by Daisy
• 8,050 points
936 views
0 votes
2 answers

Send HTTP request in Java

import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import java.io.IOException; import ...READ MORE

answered Aug 3, 2018 in Java by samarth295
• 2,190 points
179 views
0 votes
1 answer

What are optional parameters in Java

Using three dots: public void move(Object... x) { ...READ MORE

answered Apr 27, 2018 in Java by developer_1
• 3,300 points
90 views
0 votes
1 answer

Why the main() method in Java is always static?

As you might know, static here is ...READ MORE

answered May 8, 2018 in Java by geek.erkami
• 2,640 points
452 views
0 votes
2 answers

Result of character addition in Java

Binary arithmetic operations on char and byte ...READ MORE

answered Aug 22 in Java by Sirajul
• 40,990 points
75 views
0 votes
1 answer

Encode String to UTF-8

String objects in Java use the UTF-16 ...READ MORE

answered May 28, 2018 in Java by Rishabh
• 3,540 points
54 views
0 votes
2 answers

How to find out a single character appears in String or not in Java?

You can use string.indexOf('s'). If the 's' is present in string, ...READ MORE

answered Aug 7, 2018 in Java by Sushmita
• 6,880 points
79 views
0 votes
1 answer

Java URL encoding of query string parameters

I would not use URLEncoder. Besides being incorrectly ...READ MORE

answered Jun 1, 2018 in Java by Rishabh
• 3,540 points
2,646 views
+1 vote
11 answers

How to send HTTP POST requests on Java?

How to invoke Thread dump analysis API? Invoking ...READ MORE

answered Jun 16 in Java by Jim
• 810 points

reshown Jun 17 by Vardhan 27,114 views
0 votes
2 answers

Performing HTTP POST operation in JAVA

I'm using JSON-Java to build my JSON object: JSONObject json ...READ MORE

answered Nov 26, 2018 in Java by Sushmita
• 6,880 points
1,017 views