Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a JSON object over HttpClient Request with Android?

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.

My code is here

public void postData(String result,JSONObject obj) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);

    String json=obj.toString();

    try {

        HttpPost httppost = new HttpPost(result.toString());
        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se); 

        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

what mistake i have done plz correct me because it shows me an bad request error but when i do post in poster it shows me status as Successfull 200 ok

like image 900
Sachin Gurnani Avatar asked Feb 22 '12 06:02

Sachin Gurnani


People also ask

Can we send JSON object in post request?

POST requests In Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request.


1 Answers

I do this with

httppost.setHeader("Content-type", "application/json");

Also, the new HttpPost() takes the web service URL as argument.

like image 66
curioustechizen Avatar answered Sep 20 '22 15:09

curioustechizen