Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting the response body for http post request in android?

Tags:

android

Not getting the response body for http post request in android.
I am mentioning the userid, password in the name value pairs and putting in the httppost request by

postrequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

but on executing i am getting the response as SC_OK(200), but the response body is null.

One more problem is if i specify header in HTTPGet or HTTPPost's request using setHeader() function i am getting BAD REQUEST (404) response.

Please help me in resolving the above issue.

Thanks & Regards,
SSuman185

like image 830
Suman Avatar asked Nov 14 '22 03:11

Suman


1 Answers

here's a method for easy POST to a page, and getting the response as a string. The first param (the HashMap) is a key-value list of parameters you want to send. There is no error handling so you'll have to do that:

public static String doPost(HashMap<String,String> params, String url) {
        HttpPost httpost = new HttpPost(url);
        try {
            httpost.setURI(new URI(url));
        } catch (URISyntaxException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        HttpResponse response = null;

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();

        Set entryset = params.entrySet();
        Iterator iterator = entryset.iterator();
        Log.d("Posted URL: ", url+" ");
        while(iterator.hasNext()) {
            Map.Entry mapentry = (Map.Entry)iterator.next();
            String key = ((String)mapentry.getKey()).toString();
            String value = (String)mapentry.getValue();
            nvps.add(new BasicNameValuePair(key, value));

            Log.d("Posted param: ", key+" = "+value);
        }

        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            try {
                httpost.setURI(new URI(url));
            } catch (URISyntaxException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            response = getClient().execute(httpost);
            HttpEntity entity = response.getEntity();

            return convertStreamToString(entity.getContent());
        } catch (Exception e) {
            // some connection error occurred, nothing we can do
            e.printStackTrace();
        }

        return null;
    }
like image 60
zrgiu Avatar answered Dec 09 '22 18:12

zrgiu