Hari Swaminathan
Hari Swaminathan

Reputation: 616

Android - HttpURLConnection POST parameters not working

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;

}

Upvotes: 1

Views: 771

Answers (2)

Dhaval Patel
Dhaval Patel

Reputation: 10299

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.

Upvotes: 1

Orkun Kocyigit
Orkun Kocyigit

Reputation: 1147

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

...
writer.flush();
writer.close();
os.close();
urlConnection.connect();
...

Upvotes: 0

Related Questions