5

I'm using loopj's AsyncHttpClient for Android so that I can interact with a restful web application which I have created. I have tested a POST request using Postman and it works fine.

However, in Android I'm struggling to do a post request however as the content-type is always set as text/html..

    RequestParams params = new RequestParams();
    params.setUseJsonStreamer(true);
    params.put("email", "android@tester.com");
    StringEntity se = null;
    try {
        se = new StringEntity(params.toString());
        se.setContentType("application/json");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Header headers[] = {};
    if(getActivity() != null){
    RestClient.postWithContentType(getActivity(), "contacts", se, "application/json", new AsyncHttpResponseHandler() {
        //onSuccess and onFailure methods ommitted

    });

It keeps failing, and I get this message in logcat: Passed contentType will be ignored because HttpEntity sets content type.

So, I attempted to change this,

 public static void postWithContentType(Context context,String url,StringEntity s,String contentType, AsyncHttpResponseHandler responseHandler){
      s.setContentType("application/json");
      client.post(context, getAbsoluteUrl(url), s, contentType, responseHandler); 
  }

However I still get the same message, it's really frustrating, and I've been trying to figure it out for ages! If anyone has any idea about how to set the content type - it will be much appreciated,thanks!

matt
  • 285
  • 4
  • 17
  • What exactly is RestClient? You haven't said anything about that. Maybe it's implementation messes up something? – 0101100101 Sep 26 '14 at 14:49

2 Answers2

2
RequestParams requestParams = new RequestParams();
asyncHttpClient.addHeader("Accept", "text/json");
asyncHttpClient.addHeader("content-type", "application/json");
asyncHttpClient.post(context, getAbsoluteUrl(url), requestParams, new AsyncHttpResponseHandler() {
   @Override
   public void onSuccess(int statusCode, String content) {
       super.onSuccess(content
       // Ur logic
   }

   @Override
   public void onFailure(Throwable error, String content) {
       super.onFailure(error, content);
       // Ur logic
   }
});
Harsha Vardhan
  • 3,324
  • 2
  • 17
  • 22
2

I had same problem.

I cannot understand which affects it because it really works days ago. I just add header again manually and it works.

Just add RestClient.addHeader("Content-Type", "application/json"); above your RestClient.postWithContentType(...) code.

Youngjae
  • 24,352
  • 18
  • 113
  • 198