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

9

48

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?

Prattle answered 24/10, 2012 at 15:7 Comment(0)
S
130

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);
Selfness answered 16/12, 2012 at 13:19 Comment(11)
thank you! thank you!! looking for this for a while!Chaffinch
what is the responceHandler and how it call and workAppellative
Why does this need the contextGerigerianna
In my android studio it says that StringEntity is depreciated? Should I be worried, as it's still working!Vamoose
Thanks a lot I was stucked since my loopj library was updated and i had some deprecated methods.Guimond
Since version 4.2 you can use ContentType.APPLICATION_JSON.getMimeType() to get "application/json" constant.Pictorial
@Sergey Brunov Could pls tell me how to get this params in our webservice method...Gezira
@Saravanan, please consider creating a separate question.Stupefaction
Thanks A lot ,Worked with meHeronry
How to add auth headers to this request. Can you please give the exampleSibbie
you are my heroOldfangled
A
22

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

Assess answered 12/10, 2014 at 19:56 Comment(4)
while sending request it says - "Passed contentType will be ignored because HttpEntity sets content type". I am doing exactly what you have mentioned here.Precess
Thank you, thank you, thank you! setting the ContentType on BOTH the entity and post call got it working for me.Hendecagon
@SalmanKhan Yes, it's ok it still works like that. make sure you have set ContentType on both entity and post like user2408952 said.Assess
Since version 4.2 you can use ContentType.APPLICATION_JSON.getMimeType() to get "application/json" constant.Pictorial
F
7

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) {
        }
    });
Frisco answered 2/5, 2016 at 8:36 Comment(1)
This is the best if you have a service that recieve posted values from volley aswell. php code -> $data = json_decode(file_get_contents("php://input"));Fosdick
S
1

To post XML

protected void makePost() {
    AsyncHttpClient client = new AsyncHttpClient();
    Context context = this.getApplicationContext();
    String  url = URL_String;
    String  xml = XML-String;
    HttpEntity entity;
    try {
        entity = new StringEntity(xml, "UTF-8");
    } catch (IllegalArgumentException e) {
        Log.d("HTTP", "StringEntity: IllegalArgumentException");
        return;
    } catch (UnsupportedEncodingException e) {
        Log.d("HTTP", "StringEntity: UnsupportedEncodingException");
        return;
    }
    String  contentType = "string/xml;UTF-8";

    Log.d("HTTP", "Post...");
    client.post( context, url, entity, contentType, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            Log.d("HTTP", "onSuccess: " + response);
        }
          ... other handlers
    });
}
Subhead answered 17/5, 2013 at 5:51 Comment(0)
B
0

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"

Benignity answered 24/10, 2012 at 15:41 Comment(0)
I
0

If someone have a problem that httpclient send as Content-Type: text/plain, please refer this link: https://mcmap.net/q/356983/-setting-json-content-type-for-rest-client

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

Inurbane answered 17/10, 2014 at 16:54 Comment(2)
so what should I do if I want to send JSON data using loopj.Precess
@SalmanKhan // just add HttpClient.addHeader("Content-Type", "application/json"); above your .post(...); method.Inurbane
M
0

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);
Mcspadden answered 28/1, 2015 at 12:37 Comment(0)
I
0

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.

Inextinguishable answered 10/3, 2016 at 19:18 Comment(0)
S
0

To post xml file to a php server :

public class MainActivity extends AppCompatActivity {

/**
 * Send xml file to server via asynchttpclient lib
 */

Button button;
String url = "http://xxx/index.php";
String filePath = Environment.getExternalStorageDirectory()+"/Download/testUpload.xml";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button)findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            postFile();
        }
    });
}

public void postFile(){

    Log.i("xml","Sending... ");

    RequestParams params = new RequestParams();

    try {
        params.put("key",new File(filePath));
    }catch (FileNotFoundException e){
        e.printStackTrace();
    }

    AsyncHttpClient client = new AsyncHttpClient();

    client.post(url, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
            Log.i("xml","StatusCode : "+i);
        }

        @Override
        public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
            Log.i("xml","Sending failed");
        }

        @Override
        public void onProgress(long bytesWritten, long totalSize) {
            Log.i("xml","Progress : "+bytesWritten);
        }
    });
}

}

After adding android-async-http-1.4.9.jar to android studio, go to build.gradle and add : compile 'com.loopj.android:android-async-http:1.4.9' under dependencies

And on AndroidManifest.xml add:

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Sniff answered 25/5, 2016 at 10:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.