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

2019-01-10 04:50发布

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: -

<request>
  <notes>Test api support</notes>
  <hours>3</hours>
  <project_id type="integer">3</project_id>
  <task_id type="integer">14</task_id>
  <spent_at type="date">Tue, 17 Oct 2006</spent_at>
</request>

As per the documentation, I tried doing it using RequestParams, but it is failing. Is this any other way to do it? I can POST equivalent JSON too. Any ideas?

9条回答
唯我独甜
2楼-- · 2019-01-10 05:26

Loopj POST examples - extended from their Twitter example:

private static AsyncHttpClient client = new AsyncHttpClient();

To post normally via RequestParams:

RequestParams params = new RequestParams();
params.put("notes", "Test api support"); 
client.post(restApiUrl, params, responseHandler);

To post JSON:

JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, restApiUrl, entity, "application/json",
    responseHandler);
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-10 05:29

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.

查看更多
迷人小祖宗
4楼-- · 2019-01-10 05:33

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"

查看更多
登录 后发表回答