269

I am trying to do POST with HttpURLConnection(I need to use it this way, can't use HttpPost) and I'd like to add parameters to that connection such as

post.setEntity(new UrlEncodedFormEntity(nvp));

where

nvp = new ArrayList<NameValuePair>();

having some data stored in. I can't find a way how to add this ArrayList to my HttpURLConnection which is here:

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);

The reason for that awkward https and http combination is the need for not verifying the certificate. That is not a problem, though, it posts the server well. But I need it to post with arguments.

Any ideas?


Duplicate Disclaimer:

Back in 2012, I had no idea how parameters were inserted into an HTTP POST request. I was hanging on to NameValuePair because it was in a tutorial. This question might seem like a duplicate, however, my 2012 self read that other question and it was NOT using NameValuePair. It did not, in fact, solve my problem.

Michal
  • 14,455
  • 9
  • 68
  • 97
  • 2
    If you have problem with posting params then below link may help you. http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests – Hitendra Mar 19 '12 at 09:51
  • 1
    String url = "http://example.com"; String charset = "UTF-8"; String param1 = "value1"; String param2 = "value2"; // ... String query = String.format("param1=%s&param2=%s", URLEncoder.encode(param1, charset), URLEncoder.encode(param2, charset)); you can make a query string instead of using NameValuePair List. – Hitendra Mar 19 '12 at 10:06
  • "I need to use it this way, can't use HttpPost" that's why i have suggested this else answer posted by Manikandan works fine. – Hitendra Mar 19 '12 at 10:33
  • I have a question/doubt regarding for complex type of parameters. I have parameters, and i don't know how to pass those parameters. `{"key1":"value1", "key2":"value2", "key3":{"inner key1":"inner value1", "inner key2":"inner value 2"}}`. I have been provided this type of complex key value parameters and i want to know how can i pass these parameters in webservice? – Krups May 14 '16 at 09:51
  • Related: http://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily – AlikElzin-kilaka May 19 '16 at 09:06
  • 3
    Possible duplicate of [Java - sending HTTP parameters via POST method easily](https://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily) – rogerdpack May 24 '18 at 17:56
  • @rogerdpack why marking this question as a duplicate, when you linked your answer (from 2015) to an answer that is here? Exactly for the reason I posted in this question in 2012 - usage of `NameValuePair`. – Michal May 25 '18 at 12:41
  • 1
    It was because "many of the answers" here were the same as the answers to that question. But now I see that it's a different question, thanks for the clarification :) – rogerdpack May 25 '18 at 13:53

16 Answers16

369

You can get output stream for the connection and write the parameter query string to it.

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

...

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}
Michel Ayres
  • 5,357
  • 8
  • 55
  • 92
tomusiaka
  • 4,042
  • 1
  • 12
  • 5
  • 27
    NameValuePair can be substitued with AbstractMap's SimpleEntry too. See this page: http://stackoverflow.com/questions/2973041/a-keyvaluepair-in-java –  Jan 30 '13 at 19:54
  • Here are the imports if you're unsure. import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; – WoodenKitty Oct 27 '14 at 02:40
  • Isn't the POST body string UTF-8 encoded twice here? – Lennart Rolland Nov 23 '14 at 13:32
  • 10
    For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency. – Muhammad Babar Nov 24 '14 at 13:46
  • 11
    NameValuePair is deprecated in Api 22, check my answer http://stackoverflow.com/a/29561084/4552938 – Fahim Apr 14 '15 at 08:21
  • I managed to get this working, But there are no comments. Could somebody please explain what each step is doing? especially the OutputStream and BufferedWriter parts. Thanks! – Logic1 May 29 '15 at 18:31
  • UTF-8 is needed only if data is encoded like that.. Isn't it..?? – Ramesh-X Oct 08 '15 at 12:10
  • 1
    Maybe you can use raw mode when building URL object, something like this: `URL url = new URL("http://yoururl.com?k1=v1&k2=v2&···&kn=vn");` then when set conn to use POST method don't need to write them. – alexscmar Nov 27 '15 at 10:34
  • This code potentially raises a lot of exceptions and does not handle response – Anton Duzenko Mar 04 '16 at 14:19
  • I had to add `connection.getResponseCode()` in order to see this request in the server. – user3734429 Mar 16 '16 at 09:12
  • I want download PDF file Using the URL with set header and post parameter how can i do – Dilip Mar 16 '16 at 14:48
  • BasicNameValuePair deprecated ! –  Apr 06 '16 at 15:38
  • I like using `android.util.Pair` as suggested [here](http://stackoverflow.com/questions/29378012/namevaluepair-deprecated-for-openconnection). – Bjørn Stenfeldt Nov 24 '16 at 22:12
  • Be aware that regarding android only async posts are allowed. You find code that works [here](https://stackoverflow.com/questions/35886591/example-of-post-request-in-android-studio). – Mill Jan 27 '18 at 14:15
  • @tomusiaka conn.connect(); is needed? HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); already open the socket & read & write the data. – Zala Janaksinh Feb 21 '18 at 05:52
  • is HttpsURLConnection is persistent or not? – SRam May 29 '18 at 16:06
  • Your answer is for HttpsUrlConnection and the question is about HttpUrlConnection. – Mehdi Apr 05 '19 at 20:29
191

Since the NameValuePair is deprecated. Thought of sharing my code

public String  performPostCall(String requestURL,
            HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

....

  private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
Fahim
  • 11,496
  • 4
  • 36
  • 56
158

If you don't need the ArrayList<NameValuePair> for parameters, this is a shorter solution that builds the query string using the Uri.Builder class:

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();

conn.connect();
dakshbhatt21
  • 3,318
  • 3
  • 27
  • 37
mpolci
  • 2,849
  • 1
  • 20
  • 16
  • 9
    this should be an answer, as no re-inventing of the wheel must be done! – injecteer Nov 26 '15 at 15:07
  • 1
    how to upload filebody in appendqueryparameter for images and all – Harsha Dec 17 '15 at 08:51
  • 2
    more satisfying solution – PYPL Mar 24 '16 at 12:12
  • @mpolci, I have a question/doubt regarding for complex type of parameters. I have parameters, and i don't know how to pass those parameters. {"key1":"value1", "key2":"value2", "key3":{"inner key1":"inner value1", "inner key2":"inner value 2"}}. I have been provided this type of complex key value parameters and i want to know how can i pass these parameters in webservice? – Krups May 14 '16 at 09:55
  • 1
    @Krups I think your problem is different from this, try to look for sending JSON object using POST – mpolci May 14 '16 at 17:31
  • A lot better approach. Thank you much. – Gaurav Jun 16 '16 at 17:31
  • This is the best approach instead of creating arrays of pairs – Michael Knight Jul 14 '17 at 02:33
25

One solution is to make your own params string.

This is the actual method I've been using for my latest project. You need to change args from hashtable to namevaluepair's:

private static String getPostParamString(Hashtable<String, String> params) {
    if(params.size() == 0)
        return "";

    StringBuffer buf = new StringBuffer();
    Enumeration<String> keys = params.keys();
    while(keys.hasMoreElements()) {
        buf.append(buf.length() == 0 ? "" : "&");
        String key = keys.nextElement();
        buf.append(key).append("=").append(params.get(key));
    }
    return buf.toString();
}

POSTing the params:

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));
Pang
  • 8,605
  • 144
  • 77
  • 113
14

I think I found exactly what you need. It may help others.

You can use the method UrlEncodedFormEntity.writeTo(OutputStream).

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvp); 
http.connect();

OutputStream output = null;
try {
  output = http.getOutputStream();    
  formEntity.writeTo(output);
} finally {
 if (output != null) try { output.close(); } catch (IOException ioe) {}
}
Samuel
  • 839
  • 10
  • 19
14

The accepted answer throws a ProtocolException at:

OutputStream os = conn.getOutputStream();

because it does not enable the output for the URLConnection object. The solution should include this:

conn.setDoOutput(true);

to make it work.

wojciii
  • 4,095
  • 1
  • 27
  • 37
Victor Caveda
  • 636
  • 1
  • 6
  • 6
13

If it's not too late, I'd like to share my code

Utils.java:

public static String buildPostParameters(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (hashMap != null) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        }

        return output;
    }

public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
        URL url = new URL(apiAddress);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals("GET"));
        urlConnection.setRequestMethod(method);

        urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);        

        urlConnection.setRequestProperty("Content-Type", mimeType);
        OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        writer.write(requestBody);
        writer.flush();
        writer.close();
        outputStream.close();            

        urlConnection.connect();

        return urlConnection;
    }

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new APIRequest().execute();
}

private class APIRequest extends AsyncTask<Void, Void, String> {

        @Override
        protected Object doInBackground(Void... params) {

            // Of course, you should comment the other CASES when testing one CASE

            // CASE 1: For FromBody parameter
            String url = "http://10.0.2.2/api/frombody";
            String requestBody = Utils.buildPostParameters("'FromBody Value'"); // must have '' for FromBody parameter
            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                InputStream inputStream;
                // get stream
                if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                return response;
            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            // CASE 2: For JSONObject parameter
            String url = "http://10.0.2.2/api/testjsonobject";
            JSONObject jsonBody;
            String requestBody;
            HttpURLConnection urlConnection;
            try {
                jsonBody = new JSONObject();
                jsonBody.put("Title", "BNK Title");
                jsonBody.put("Author", "BNK");
                jsonBody.put("Date", "2015/08/08");
                requestBody = Utils.buildPostParameters(jsonBody);
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (JSONException | IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }           

            // CASE 3: For form-urlencoded parameter
            String url = "http://10.0.2.2/api/token";
            HttpURLConnection urlConnection;
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("grant_type", "password");
            stringMap.put("username", "username");
            stringMap.put("password", "password");
            String requestBody = Utils.buildPostParameters(stringMap);
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }                  
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);
            // do something...
        }
    }
BNK
  • 22,674
  • 8
  • 69
  • 81
  • @Srinivasan as you see in my code: "if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { ... } else { ... } " – BNK Dec 07 '15 at 10:22
  • Ya i already got that but what i asked was which variable will have whole response from the given url – iSrinivasan27 Dec 07 '15 at 10:25
  • 1
    @Srinivasan more detail you can try InputStream inputStream = null; if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } – BNK Dec 07 '15 at 10:27
  • @Srinivasan actually, if resp code < 400 (Bad Request), you use getInputStream, if >=400, getErrorStream – BNK Dec 07 '15 at 10:29
  • Ya i know it. I misunderstood with response in postExecute() – iSrinivasan27 Dec 07 '15 at 10:31
  • @Srinivasan I'll update my code tommorow, now I am on mobile so it's difficult to do that. Thanks for your comments – BNK Dec 07 '15 at 10:34
  • @Srinivasan: I have just updated my answer, hope it's clearer :) – BNK Dec 08 '15 at 01:23
  • 1
    Super Stuff Bro Good Examples – Whats Going On Feb 15 '19 at 05:24
11

There's a much easier approach using PrintWriter (see here)

Basically all you need is:

// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// write out form parameters
String postParamaters = "param1=value1&param2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

// connect
urlConnection.connect();
Marchy
  • 2,498
  • 4
  • 34
  • 26
4

AsyncTask to send data as JSONObect via POST Method

public class PostMethodDemo extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setRequestMethod("POST");

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ());

                try {
                    JSONObject obj = new JSONObject();
                    obj.put("key1" , "value1");
                    obj.put("key2" , "value2");

                    wr.writeBytes(obj.toString());
                    Log.e("JSON Input", obj.toString());
                    wr.flush();
                    wr.close();
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                urlConnection.connect();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e("Response", "" + server_response);
        }
    }

    public static String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }
Bhargav Thanki
  • 4,552
  • 2
  • 31
  • 43
3

Try this:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user_name", "Name"));
nameValuePairs.add(new BasicNameValuePair("pass","Password" ));
nameValuePairs.add(new BasicNameValuePair("user_email","email" ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

String ret = EntityUtils.toString(response.getEntity());
Log.v("Util response", ret);

You can add as many nameValuePairs as you need. And don't forget to mention the count in the list.

qqx
  • 16,583
  • 2
  • 57
  • 67
Manikandan
  • 2,421
  • 4
  • 48
  • 88
2

To call POST/PUT/DELETE/GET Restful methods with custom header or json data the following Async class can be used

public class HttpUrlConnectionUtlity extends AsyncTask<Integer, Void, String> {
private static final String TAG = "HttpUrlConnectionUtlity";
Context mContext;
public static final int GET_METHOD = 0,
        POST_METHOD = 1,
        PUT_METHOD = 2,
        HEAD_METHOD = 3,
        DELETE_METHOD = 4,
        TRACE_METHOD = 5,
        OPTIONS_METHOD = 6;
HashMap<String, String> headerMap;

String entityString;
String url;
int requestType = -1;
final String timeOut = "TIMED_OUT";

int TIME_OUT = 60 * 1000;

public HttpUrlConnectionUtlity (Context mContext) {
    this.mContext = mContext;
    this.callback = callback;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(Integer... params) {
    int requestType = getRequestType();
    String response = "";
    try {


        URL url = getUrl();
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection = setRequestMethod(urlConnection, requestType);
        urlConnection.setConnectTimeout(TIME_OUT);
        urlConnection.setReadTimeout(TIME_OUT);
        urlConnection.setDoOutput(true);
        urlConnection = setHeaderData(urlConnection);
        urlConnection = setEntity(urlConnection);

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response = readResponseStream(urlConnection.getInputStream());
            Logger.v(TAG, response);
        }
        urlConnection.disconnect();
        return response;


    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (SocketTimeoutException e) {
        return timeOut;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Logger.e(TAG, "ALREADY CONNECTED");
    }
    return response;
}

@Override
protected void onPostExecute(String response) {
    super.onPostExecute(response);

    if (TextUtils.isEmpty(response)) {
        //empty response
    } else if (response != null && response.equals(timeOut)) {
        //request timed out 
    } else    {
    //process your response
   }
}


private String getEntityString() {
    return entityString;
}

public void setEntityString(String s) {
    this.entityString = s;
}

private String readResponseStream(InputStream in) {
    BufferedReader reader = null;
    StringBuffer response = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

private HttpURLConnection setEntity(HttpURLConnection urlConnection) throws IOException {
    if (getEntityString() != null) {
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(getEntityString());
        writer.flush();
        writer.close();
        outputStream.close();
    } else {
        Logger.w(TAG, "NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setHeaderData(HttpURLConnection urlConnection) throws UnsupportedEncodingException {
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setRequestProperty("Accept", "application/json");
    if (getHeaderMap() != null) {
        for (Map.Entry<String, String> entry : getHeaderMap().entrySet()) {
            urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    } else {
        Logger.w(TAG, "NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setRequestMethod(HttpURLConnection urlConnection, int requestMethod) {
    try {
        switch (requestMethod) {
            case GET_METHOD:
                urlConnection.setRequestMethod("GET");
                break;
            case POST_METHOD:
                urlConnection.setRequestMethod("POST");
                break;
            case PUT_METHOD:
                urlConnection.setRequestMethod("PUT");
                break;
            case DELETE_METHOD:
                urlConnection.setRequestMethod("DELETE");
                break;
            case OPTIONS_METHOD:
                urlConnection.setRequestMethod("OPTIONS");
                break;
            case HEAD_METHOD:
                urlConnection.setRequestMethod("HEAD");
                break;
            case TRACE_METHOD:
                urlConnection.setRequestMethod("TRACE");
                break;
        }
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
    return urlConnection;
}

public int getRequestType() {
    return requestType;
}

public void setRequestType(int requestType) {
    this.requestType = requestType;
}

public URL getUrl() throws MalformedURLException {
    return new URL(url);
}

public void setUrl(String url) {
    this.url = url;
}

public HashMap<String, String> getHeaderMap() {
    return headerMap;
}

public void setHeaderMap(HashMap<String, String> headerMap) {
    this.headerMap = headerMap;
}   }

And The Usage is

    HttpUrlConnectionUtlity httpMethod = new HttpUrlConnectionUtlity (mContext);
    JSONObject jsonEntity = new JSONObject();

    try {
        jsonEntity.put("key1", value1);
        jsonEntity.put("key2", value2);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    httpMethod.setUrl(YOUR_URL_STRING);
    HashMap<String, String> headerMap = new HashMap<>();
    headerMap.put("key",value);
    headerMap.put("key1",value1);
    httpMethod.setHeaderMap(headerMap);
    httpMethod.setRequestType(WiseConnectHttpMethod.POST_METHOD); //specify POST/GET/DELETE/PUT
    httpMethod.setEntityString(jsonEntity.toString());
    httpMethod.execute();
Muhamed Riyas M
  • 4,707
  • 3
  • 24
  • 29
1

In my case I have created function like this to make Post request which takes String url and hashmap of parameters

 public  String postRequest( String mainUrl,HashMap<String,String> parameterList)
{
    String response="";
    try {
        URL url = new URL(mainUrl);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : parameterList.entrySet())
        {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        byte[] postDataBytes = postData.toString().getBytes("UTF-8");




        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0; )
            sb.append((char) c);
        response = sb.toString();


    return  response;
    }catch (Exception excep){
        excep.printStackTrace();}
    return response;
}
Rahul_Pawar
  • 523
  • 1
  • 8
  • 14
1

By using org.apache.http.client.HttpClient also you can easily do this with more readable way as below.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

Within try catch you can insert

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
M P Mathugama
  • 1,258
  • 1
  • 18
  • 30
0

Parameters to HttpURLConnection using POST using NameValuePair with OutPut

        try {
        URL url = new URL("https://yourUrl.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json");

        JSONObject data = new JSONObject();
        data.put("key1", "value1");
        data.put("key2", "value2");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
Kishan Solanki
  • 8,893
  • 2
  • 51
  • 54
0

I use something like this:

SchemeRegistry sR = new SchemeRegistry();
sR.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

HttpParams params = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params, sR);

HttpClient httpclient = new DefaultHttpClient(mgr, params);

HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
Lakhwinder Singh
  • 5,084
  • 5
  • 24
  • 47
Vyacheslav Shylkin
  • 9,491
  • 5
  • 36
  • 34
-1
JSONObject params = new JSONObject();
try {
   params.put(key, val);
}catch (JSONException e){
   e.printStackTrace();
}

this is how i pass "params"(JSONObject) through POST

connection.getOutputStream().write(params.toString().getBytes("UTF-8"));