1

I am using HttpURLConnection for communicating with web service in one of my android App, GET method & parameters are submitted correctly but when I tried to POST request the POST parameters are not submitted in the request. I have attached the method used, please guide me where I am going wrong.

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String request_url, int method,
                              Map<String,String> params) {
    InputStream inputStream = null;

    HttpURLConnection urlConnection = null;

    Integer result = 0;
    try {
        URL url = new URL(request_url);
        urlConnection = (HttpURLConnection) url.openConnection();
        //urlConnection.setRequestProperty("Content-Type", "application/xml");
        //urlConnection.setRequestProperty("Accept", "application/xml");
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        if (method == GET) {
            urlConnection.setRequestMethod("GET");
        } else if(method == POST) {
            urlConnection.setRequestMethod("POST");
            String urlParameters = null;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                if(urlParameters != null)
                {
                    urlParameters += "&";
                }
                urlParameters +=entry.getKey() +"="+ URLEncoder.encode(entry.getValue(), "UTF-8");
            }
            Log.d(TAG, "urlParameters: "+urlParameters);
            //Send request
            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(urlParameters);
            writer.flush ();
            writer.close ();
        }
        int statusCode = urlConnection.getResponseCode();
        if (statusCode == HttpsURLConnection.HTTP_OK) {

            inputStream = new BufferedInputStream(urlConnection.getInputStream());

            response = convertInputStreamToString(inputStream);


            result = 1; // Successful

        } else {
            result = 0; //"Failed to fetch data!";
        }

    } catch (Exception e) {
        Log.d(TAG, ""+e.getLocalizedMessage());
        e.printStackTrace();
    }
    Log.d(TAG, ""+response);
    return response;

}
ArtKorchagin
  • 4,801
  • 13
  • 42
  • 58
Hari Swaminathan
  • 616
  • 1
  • 13
  • 27

2 Answers2

1

Change your urlParameters formation logic with below code:

StringBuilder result = new StringBuilder();
try {
    for (Map.Entry<String, String> param : params.entrySet()){
        if (result.toString().length() !=0) {
            result.append("&");
        }
        result.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(param.getValue(), "UTF-8"));
     }
} catch (UnsupportedEncodingException e) {
     e.printStackTrace();
}

In your code

 urlParameters = null;
 urlParameters +=entry.getKey() +"="+ URLEncoder.encode(entry.getValue(), "UTF-8");

Will add null string at the start of urlParameters. it's recommended to use StringBuilder for String concatenation while using in loop.

1615903
  • 32,635
  • 12
  • 70
  • 99
Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
  • how bout if params value contain character `&` like this http://stackoverflow.com/questions/38418389/httpsurlconnection-and-volley-difference any suggestion? – Iqbal Rizky Jul 17 '16 at 06:47
0

Try to close your OutputStream and call httpURLConnection.connect() after you are done with your writer:

...
writer.flush();
writer.close();
os.close();
urlConnection.connect();
...
Orkun Kocyigit
  • 1,137
  • 10
  • 21
  • Tried but no difference. BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(urlParameters); writer.flush (); writer.close (); os.close(); urlConnection.connect(); – Hari Swaminathan Nov 18 '15 at 09:39