Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Json content-type for Rest client

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", "[email protected]");
    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!

like image 799
matt Avatar asked Sep 29 '22 18:09

matt


1 Answers

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
   }
});
like image 94
Harsha Vardhan Avatar answered Oct 05 '22 07:10

Harsha Vardhan