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

时间:2015-01-25 21:48:05

标签: java android http http-headers

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

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

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

HttpResponse httpResponse = httpclient.execute(httpPost);

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

PS我发送简单的JSON对象

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

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

1 个答案:

答案 0 :(得分:3)

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

修改

我尝试了部分代码。我没有设置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;
    }
}

我使用wireshark并且可以验证以下请求将转到百度:

  

POST / HTTP / 1.1
  接受:application / json
  Content-Type:application / json;
  内容长度:20
  主持人:www.baidu.com
  连接:保持活力
  User-Agent:Apache-HttpClient / 4.3.6(java 1.5)

     

{"电话":&#34 + 8912345"}

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