我应该为 POST HTTP 请求的 Content-Length 使用什么值?

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

我正在尝试发送 HTTP 请求。目前我坚持添加 Content-Length 属性:我有

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

如果我评论最后一行 (content-length) 服务器 returns 我的错误,我错过了 smth,我最后一行保持未评论 - 然后我在尝试做时捕获异常

HttpResponse httpResponse = httpclient.execute(httpPost);

请告诉我我在设置 headers 时做错了什么。

PS我发的很简单JSONobject

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

我的 post 方法的完整代码片段:

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;
    }

您能否详细说明服务器错误代码是什么以及发生异常时的堆栈跟踪?

编辑:

我试过你的部分代码。我没有设置内容长度(因为这应该自动完成):

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;
    }
}

我用了wireshark,可以验证下面的请求是去百度的:

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"}

这表明请求发送正常,这意味着客户端似乎没有问题。这就是为什么我建议检查服务器端是否有错误。正如我已经提到的,我认为您应该使用 tcpdump 或 wireshark 来检查客户端和服务器之间的流量。这可能会让您更好地了解问题所在。