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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28141947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:03:53  来源:igfitidea点击:

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

javaandroidhttphttp-headers

提问by Anton Kizema

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

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

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

如果我评论最后一行(内容长度)服务器返回我错过 smth 的错误,我最后一行保持未注释 - 然后我在尝试执行时捕获异常

HttpResponse httpResponse = httpclient.execute(httpPost);

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

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

PS I am sending easy JSON object

PS我正在发送简单的JSON对象

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

回答by fishi0x01

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):

我尝试了您代码的一部分。我没有设置 Content-Length (因为这应该自动完成):

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:

我使用了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"}

POST / HTTP/1.1
接受:application/json
内容类型:application/json;
内容长度:20
主机:www.baidu.com
连接:Keep-Alive
User-Agent:Apache-HttpClient/4.3.6 (java 1.5)

{“电话”:“+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.

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