Search code examples
javaandroidjsonandroid-async-httploopj

How to send data in json format using AndroidAsyncHttp


I am trying to send data via post method of AsyncHttpClient in json format to server, server accept this format

{
  email : '[email protected]'
  password:'xxxxxx'
  'username:'John Doe'
  'lastname:'john'
}

and this is my code

JSONObject params = new JSONObject();
params.put("last_name","Karimi");
params.put("username","zahid");
params.put("email","[email protected]");
params.put("password","1234566");

StringEntity entity = new StringEntity(params.toString());
Log.d("entity3",entity+"");

String url = "http://192.168.100.12/users";

client.post(context, url, entity, "application/json", handler);

when I log the entity the result is shown as below

[Content-Type: text/plain; charset=ISO-8859-1,Content-Length: 496,Chunked: false]

please help me?


Solution

  • I also use this AsyncHttpClient

    the way i send json data is

       // postData = your json data
    
        ByteArrayEntity entity = null;
        try {
            entity = new ByteArrayEntity(postData.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    
        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    
        asyncHttpClient.post(getActivity(), url, entity, "application/json", new AsyncHttpResponseHandler() {
    

    Which works fine for me.. hope this will help..