How to send a JSON object over Request with Android?

前端 未结 8 2007
慢半拍i
慢半拍i 2020-11-22 03:32

I want to send the following JSON text

{\"Email\":\"aaa@tbbb.com\",\"Password\":\"123456\"}

to a web service and read the response. I kno

8条回答
  •  不要未来只要你来
    2020-11-22 03:58

    There's a surprisingly nice library for Android HTTP available at the link below:

    http://loopj.com/android-async-http/

    Simple requests are very easy:

    AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://www.google.com", new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            System.out.println(response);
        }
    });
    

    To send JSON (credit to `voidberg' at https://github.com/loopj/android-async-http/issues/125):

    // params is a JSONObject
    StringEntity se = null;
    try {
        se = new StringEntity(params.toString());
    } catch (UnsupportedEncodingException e) {
        // handle exceptions properly!
    }
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    
    client.post(null, "www.example.com/objects", se, "application/json", responseHandler);
    

    It's all asynchronous, works well with Android and safe to call from your UI thread. The responseHandler will run on the same thread you created it from (typically, your UI thread). It even has a built-in resonseHandler for JSON, but I prefer to use google gson.

提交回复
热议问题