how to make httpPost call with json encoded body?

后端 未结 2 663
栀梦
栀梦 2020-12-03 15:31

i am using following code to make an httpPost call but it is returning me 400 bad request when i try to give following parameters in \"simple rest client\" in chrome extensi

相关标签:
2条回答
  • 2020-12-03 15:55

    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;
    
    0 讨论(0)
  • 2020-12-03 16:01

    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.

    0 讨论(0)
提交回复
热议问题