POSTing JSON/XML using android-async-http (loopj)
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);
@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 :)
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) { } });