Anton Kizema
Anton Kizema

Reputation: 1092

What value should I use for Content-Length of an POST HTTP request?

I am trying to send HTTP request. Currently I am stuck on adding Content-Length property: I have

httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.addHeader("Content-Length", ""+json.length() );

If i comment last line (content-length) server returns me error that I miss smth, I last line stays uncommented - then I catch an exception when trying to do

HttpResponse httpResponse = httpclient.execute(httpPost);

Please, tell me what am I doing wrong with setting headers.

PS I am sending easy JSON object

 JSONObject jsonObject = new JSONObject();
 jsonObject.accumulate("phone", phone);

My full code snippet of post metod:

public static JSONObject POST(String url, String phone){
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            // 3. build jsonObject
            Log.d("ANT", "JSONObject jsonObject = new JSONObject(); PHONE:"+phone);
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("phone", phone);

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            Log.d("ANT", "json"+json.length());

            // 7. Set some headers to inform server about the type of the content

            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;");
//            httpPost.addHeader("Content-Length", ""+json.length() );


            // 8. Execute POST request to the given URL
            Log.d("ANT", "httpPost:"+getStringFromInputStream(httpPost.getEntity().getContent()));
            for (Header s : httpPost.getAllHeaders())
                Log.i("ANT", "header::"+s.getName() + ":"+s.getValue());


            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            Log.d("ANT", "httpResponse.getEntity().getContent();");

            // 10. convert inputstream to string
            if (inputStream != null) {
                result = getStringFromInputStream(inputStream);
                Log.d("ANT", "getStringFromInputStream : "+result);
                JSONObject obj = new JSONObject(result);
                Log.d("ANT", "JSONObject");
                return obj;
            }
            else
                result = "Did not work!";

        } catch (ClientProtocolException e) {
            Log.d("ANT", "ClientProtocolException : "+ e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("ANT", "IOException:"+ e.getLocalizedMessage());
        } catch (Exception e) {
            Log.d("ANT", "Exception:"+ e.getLocalizedMessage());
        }

        // 11. return result
        return null;
    }

Upvotes: 1

Views: 22569

Answers (1)

fishi0x01
fishi0x01

Reputation: 3759

Can you elaborate on what the server error code is and a stack trace when the exception occurs?

Edit:

I tried some part of your code. I did not set the Content-Length (since this should be done automatically):

public class App 
{
    public static void main( String[] args )
    {
        post("http://www.baidu.com","+8912345");
    }

    public static JSONObject post(String url, String phone){
        InputStream inputStream = null;
        String result = "";

        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("phone", phone);

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;");

            // 8. Execute
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

        } catch (ClientProtocolException e) {
            System.out.println("ClientProtocolException : "+e.getLocalizedMessage());
        } catch (IOException e) {
            System.out.println("IOException:"+ e.getLocalizedMessage());
        } catch (Exception e) {
            System.out.println("Exception:"+ e.getLocalizedMessage());
        }

        return null;
    }
}

I used wireshark and could verify that the following request is going to baidu:

POST / HTTP/1.1
Accept: application/json
Content-Type: application/json;
Content-Length: 20
Host: www.baidu.com
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.6 (java 1.5)

{"phone":"+8912345"}

This shows that the request is sent properly, which means the client side seems to be fine. That's why I would suggest to check the server side for errors. As I already mentioned I think you should use tcpdump or wireshark to check the traffic between client and server. This might give you a better understanding of what is going wrong.

Upvotes: 4

Related Questions