开发者

how to make httpPost call with json encoded body?

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 extension it works fine any one guide me what mistake am i doing here?

Simple rest Client I entered the following:

URL: http://jon2012.com/api/register Method: POST Headers: No headers, as they are not required Data: { "email": "test@example.com", "first_name":"Name" }

how to make httpPost call with json encoded body?

Android Code:

HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
        HttpResponse response;
        JSONObject json = new JSONObject();
        try{
            HttpPost post = new HttpPost(url);
            json.p开发者_开发问答ut("email", email);
            json.put("first_name", name);
            StringEntity se = new StringEntity( "JSON: " + json.toString());  
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(se);
            response = client.execute(post);
            /*Checking response */
            /*if(response!=null){
                InputStream in = response.getEntity().getContent(); //Get the data in the entity
*/
            int statusCode = response.getStatusLine().getStatusCode();

        }
        catch(Exception e){
            e.printStackTrace();
           // createDialog("Error", "Cannot Estabilish Connection");
        }

any help would be appriciated


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 the 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜