how to make httpPost call with json encoded body?

橙三吉。 提交于 2019-11-27 14:46:51

i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name

my code

boolean result = false;
        HttpClient hc = new DefaultHttpClient();
        String message;

        HttpPost p = new HttpPost(url);
        JSONObject object = new JSONObject();
        try {

            object.put("updates", updates);
            object.put("mobile", mobile);
            object.put("last_name", lastname);
            object.put("first_name", firstname);
            object.put("email", email);

        } catch (Exception ex) {

        }

        try {
        message = object.toString();


        p.setEntity(new StringEntity(message, "UTF8"));
        p.setHeader("Content-type", "application/json");
            HttpResponse resp = hc.execute(p);
            if (resp != null) {
                if (resp.getStatusLine().getStatusCode() == 204)
                    result = true;
            }

            Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
        } catch (Exception e) {
            e.printStackTrace();

        }

        return result;

Here's my code for calling rest services with Http POST and JSON:

(Note that I'm using AndroidHttpClient, which's basically a DefaultHttpClient with some preset attributes, and Google's GSON project for JSON marshalling)

Class for handling communication:

public class NetworkComm extends AsyncTask<String, Integer, String> {

    // Log tag
    private static final String TAG = "NetworkComm";

    private AndroidHttpClient hc;
    private HttpContext localContext;
    private TaskResponseListener listener;
    private int reqType;
    private String message;
    private String url;
    private Object extra;

    public NetworkComm(AndroidHttpClient hc, HttpContext localContext, TaskResponseListener listener, 
            int reqType, String message, String url, Object extra){
        super();

        this.hc = hc;
        this.localContext = localContext;
        this.listener = listener;
        this.reqType = reqType;
        this.message = message;
        this.url = url;
        this.extra = extra;
    }

    public AndroidHttpClient getHc() {
        return hc;
    }

    public void setHc(AndroidHttpClient hc) {
        this.hc = hc;
    }

    public HttpContext getLocalContext() {
        return localContext;
    }

    public void setLocalContext(HttpContext localContext) {
        this.localContext = localContext;
    }

    public void start(){
        this.execute(message);
    }

    protected void onPreExecute() {
        //Don't do anything here
    }

    protected String doInBackground(String... req) {

        Log.d(TAG, "Message to send: "+req[0]);
        HttpPost p = new HttpPost(url);

        try{
            p.setEntity(new StringEntity(req[0], "UTF8"));
        }catch(Exception e){
            e.printStackTrace();
        }
        p.setHeader("Content-type", "application/json");

        String response = "";
        try{
            HttpResponse resp = hc.execute(p, localContext);
            InputStream is = resp.getEntity().getContent();
            response = convertStreamToString(is);
            Log.d("Response", "Response is " + response);

            Log.d("Status line", ""+resp.getStatusLine().getStatusCode());
        } catch (Exception e){
            e.printStackTrace();
        }

        return response;
     }

     protected void onProgressUpdate(Integer... progress) {
         // dont handle this yet
     }

     @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    protected void onPostExecute(String result) {
         Log.d("task", "task finished");
         listener.onTaskResponse(reqType, result, extra);
     }

     public interface TaskResponseListener{
         public void onTaskResponse(int type, String response, Object extra);
     }

     private String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {        
            return "";
        }
     }
}

Usage:

Gson g = new Gson();
        SomeContent content = new SomeContent("Stuff", 4);
        String message = g.toJson(content);

        NetworkComm task = new NetworkComm(hc, localContext, listener, 0, message, url, "");
        task.start();

Hope that this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!