Search code examples
androidweb-servicesandroidhttpclientandroid-async-httploopj

AsyncHttpClient﹕ Passed contentType will be ignored because HttpEntity sets content type


Im trying to post some data using the android httpclient (loopj).I add some json data in its body and i set request header.But it shows AsyncHttpClient﹕ Passed contentType will be ignored because HttpEntity sets content type. Does any one know how to solve this issue?

 public static void post(Activity context,String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        try {
            JSONObject jsonParams = new JSONObject();
            JSONObject innerObject = new JSONObject();
            innerObject.put("Name", "@MODE");
            innerObject.put("ParamType", "8");
            innerObject.put("Value", "0");
            JSONArray ar = new JSONArray();
            ar.put(innerObject);
            try {
                jsonParams.put("ProcName", "Core.MENUS_SPR");
                jsonParams.put("dbparams", ar);

               Log.i("jsonParams.toString()",""+jsonParams.toString());

                StringEntity se = null;
                try {
                    se = new StringEntity(jsonParams.toString());


                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return;
                }
                   client.post(context, (url), se, "application/json", responseHandler);


            } catch (JSONException e) {
                e.printStackTrace();
            }

      } catch (Exception e) {
            e.printStackTrace();
        }

    }

Solution

  • Write this before post then it will work.

    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    

    Reason once you use some entity it will ignore content type given in post and use entity's content. So, above line will solve your problem.


    I dig into the source code and find out that your content type pass in post(..) will be ignored and if it exists then you will this error in logs.

    Passed contentType will be ignored because HttpEntity sets content type

    but don't worry once you give content type to your entity it will work. For removing this this error you can pass null in content type in post(..) instead.

    Some code from AsyncHttpClient.java:

    if (contentType != null) {
                if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null) {
                    Log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type");
                } else {
                    uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType);
                }
            }