0

The following is my code for a HTTP POST request in an Android device running Android 4.1.2. I have question:

  • This code works perfectly on a Samsung device whereas it is giving "Content-type is not application/json" on an HTC device.

    public static String POST(String url, JSONObject obj) { Log.i("JSONPOSTBEGIN", "Beginning of JSON POST"); InputStream inputStream = null; String result = "";

    HttpClient httpclient = new DefaultHttpClient();
    
    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Accept", "application/json");
    
        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);
    
        HttpResponse httpResponse = mHhttpclient.execute(post);
    
        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
    
        // convert inputstream to string
        if(inputStream != null) {
            result = convertInputStreamToString(inputStream);
        } else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    Log.i("JSONPOSTEND", "End of JSON data post methos...");
    return result;
    

    }

2 Answers 2

0

For it to work on HTC and all devices, you must do this

private static HttpEntity getHttpEntity(String stringEntity) {
    HttpEntity entity = null;
    try {
        entity = new StringEntity(stringEntity, HTTP.UTF_8);
        ((StringEntity) entity).setContentType("application/json;charset=UTF-8");
        ((StringEntity) entity).setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

    } catch (Exception e) {
        Log.d("error creating entity: " + stringEntity);
    }
    return entity;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Note that headers are likely being set by this

new HttpPost(url);

and that before you add new headers like for "content-type" you may have to call remove header (Content-type) first....

you need logging to figure it all out.for more on that see accepted ans here

and get WIRE & HEADER logging up in your test environment

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.