POSTing JSON/XML using android-async-http (loopj)

前端 未结 9 785
广开言路
广开言路 2020-12-02 07:01

I am using android-async-http and really liking it. I\'ve run into a problem with POSTing data. I have to post data to the API in the following format: -

&l         


        
相关标签:
9条回答
  • 2020-12-02 07:15

    Just make JSONObject and then convert it to String "someData" and simply send with "ByteArrayEntity"

        private static AsyncHttpClient client = new AsyncHttpClient();
        String someData;
        ByteArrayEntity be = new ByteArrayEntity(someData.toString().getBytes());
        client.post(context, url, be, "application/json", responseHandler);
    

    It is working fine for me.

    0 讨论(0)
  • 2020-12-02 07:19

    just write your xml or json to a string and send to server, with proper headers or without. and yes set "Content-Type" to "application/json"

    0 讨论(0)
  • 2020-12-02 07:21

    a better way to post json

    RequestParams params = new RequestParams();
        params.put("id", propertyID);
        params.put("lt", newPoint.latitude);
        params.put("lg", newPoint.longitude);
        params.setUseJsonStreamer(true);
    
        ScaanRestClient restClient = new ScaanRestClient(getApplicationContext());
        restClient.post("/api-builtin/properties/v1.0/edit/location/", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            }
    
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            }
        });
    
    0 讨论(0)
  • 2020-12-02 07:25

    If someone have a problem that httpclient send as Content-Type: text/plain, please refer this link: https://stackoverflow.com/a/26425401/361100

    The loopj httpclient is somewhat changed (or has problem) which cannot override StringEntity native Content-Type to application/json.

    0 讨论(0)
  • 2020-12-02 07:29

    @Timothy answer did not work for me.

    I defined the Content-Type of the StringEntity to make it work:

    JSONObject jsonParams = new JSONObject();
    jsonParams.put("notes", "Test api support");
    
    StringEntity entity = new StringEntity(jsonParams.toString());
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    
    client.post(context, restApiUrl, entity, "application/json", responseHandler);
    

    Good Luck :)

    0 讨论(0)
  • 2020-12-02 07:30

    You can add the JSON string as an InputStream of some kind - I've used the ByteArrayStream, then passing it to the RequestParams you should set the correctMimeType

    InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8")));
    multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON);
    
    0 讨论(0)
提交回复
热议问题