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,310 points
100,529 views
___123___Java - sending HTTP parameters via POST method easily | Edureka Community___123___

12 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,620 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","[email protected]");
    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
0 votes

You can write like this simply get request in java code 

public static Integer sendOTP(String phone, String msg){ 

       String url = "http://example.php?user=xxx&password=sss!@&mobile="+phone+"&message="+ msg+"&sender=vxbxb&type=x";

        try {

            URL obj = new URL(url);

            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            con.getResponseCode();

            return 200;

            } catch (Exception e) {

                e.printStackTrace();

        }

}

answered Jul 7, 2020 by anonymous
• 140 points
0 votes

Below are the steps we need to follow for sending Java HTTP requests using HttpURLConnection class.

  1. Create URL object from the GET/POST URL String.
  2. Call openConnection() method on URL object that returns instance of HttpURLConnection
  3. Set the request method in HttpURLConnection instance, default value is GET.
  4. Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc.
  5. We can call getResponseCode() to get the response HTTP code. This way we know if the request was processed successfully or there was any HTTP error message thrown.
  6. For GET, we can simply use Reader and InputStream to read the response and process it accordingly.
  7. For POST, before we read response we need to get the OutputStream from 
answered Dec 11, 2020 by Rajiv
• 8,910 points

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,120 points
2,868 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,220 points
1,046 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,310 points
430 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 9, 2018 in Java by geek.erkami
• 2,680 points
1,464 views
0 votes
2 answers

Result of character addition in Java

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

answered Aug 22, 2019 in Java by Sirajul
• 59,210 points
3,016 views
0 votes
1 answer

Encode String to UTF-8

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

answered May 29, 2018 in Java by Rishabh
• 3,620 points
341 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,900 points
3,826 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,620 points
14,880 views
+1 vote
13 answers

How to send HTTP POST requests on Java?

With Apache HttpClient In the old days, this Apache ...READ MORE

answered Dec 10, 2020 in Java by Rajiv
• 8,910 points
150,153 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,900 points
3,330 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP