thurmi
thurmi

Reputation: 51

Do a HTTPPost request with JSON Body, Android

I 'm pretty new to Android. So, I 'm struggling with a HttpPost in android with Json Data.

JSONObject jsonObj = new JSONObject();
JSONObject jsonObjDasUser = new JSONObject();

    jsonObj.put("name", "Login");
    jsonObj.put("type", "request");
    jsonObj.put("UserCredential", jsonObjUserCredential );
    jsonObjUserCredential .put("username", id);
    jsonObjUserCredential .put("password", password);

// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url); 

StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);

entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();

How can I include the jsonObjUserCredential as a entity like:::

//StringEntity userCredential = new StringEntity(jsonObjUserCredential .toString(),HTTP.UTF_8);??????

What am doing wrong here?????

Please Help me....

Upvotes: 1

Views: 11505

Answers (2)

labreu
labreu

Reputation: 444

try something like this:

List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("myJSON", MyJSONObject.toString()));

//Set the http request 
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(webServiceUrl + methodName);

httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

//Variable to keep the http response
response = null;

//Set the parameters if exist
if(params != null && !params.isEmpty()){
    try {
        //Set the parameters in the request
    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
}

//Execute the call
response = httpClient.execute(httpPost,localContext);

hope it helps

Upvotes: 1

Sandeep Dhull
Sandeep Dhull

Reputation: 1648

Try this code .. Hope this fix ur problem..

JSONObject jsonObj = new JSONObject();
JSONObject jsonObjDasUser = new JSONObject();

jsonObj.put("name", "Login");
jsonObj.put("type", "request");
jsonObjUserCredential .put("username", id);
jsonObjUserCredential .put("password", password);
jsonObj.put("UserCredential", jsonObjUserCredential );

// Create the POST object and add the parameters

HttpPost httpPost = new HttpPost(url); 

StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);

Upvotes: 5

Related Questions