android - http发布内容长度(json帖子)

时间:2013-05-14 08:59:57

标签: android json post

我需要为用户登录创建一个帖子请求。我正在设置Content-Length标头但是当我发布请求时它会给出 org.apache.http.client.HttpResponseException:Length Required

我的代码

        DefaultHttpClient httpclient = new DefaultHttpClient();

        JSONObject data = new JSONObject();
        data.put("UserName", username);
        data.put("Password", password);
        data.put("RememberMe", false);

        HttpPost httpost = new HttpPost(LOGIN_PATH);
        StringEntity se = new StringEntity(data.toString());
        httpost.setEntity(se);

        httpost.setHeader("Accept", "application/json");
        httpost.setHeader("Content-Type", "application/json");
        httpost.setHeader("Content-Length",""+se.getContentLength());

        ResponseHandler responseHandler = new BasicResponseHandler();
        return httpclient.execute(httpost, responseHandler);

当我设置Content-Length标头时,它会提供'Content-Length标头已存在',当删除content-lenght标头时,它会显示'Length is required'

感谢。

1 个答案:

答案 0 :(得分:2)

更改

 httpost.setHeader("Content-Lenght",""+se.getContentLength());

 httpost.setHeader("Content-Length",""+se.getContentLength());

因为目前您传递Content-Lenght(长度拼写错误)而不是Content-Length作为setHeader方法的关键