gundumw100
gundumw100
2013-10-28 11:06

为什么使用HttpClient发送json总是返回400?

  • httppost
  • android
  • httpclient

android手机端需要发送一个json格式的数据,返回的也是json数据。
现在问题出现在,我无论怎么写都返回400,Bad Request。
问题出在哪儿呢?且看代码,感觉该设置的都设置了。
[code="java"]
/**
* POST获取服务端数据,发送的是json格式的数据
* @param urlString
* @param json 需要发送的json数据
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String getDataFromServerByPostForJson(String urlString,JSONObject json) throws ClientProtocolException, IOException{
String strResult = null;
HttpClient client = new DefaultHttpClient();

    StringEntity entity = new StringEntity(json.toString());
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));//"application/octet-stream"
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,HTTP.UTF_8));

    HttpPost post = new HttpPost(urlString);
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-Type", "application/json");
    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        strResult = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
    }else{
        post.abort();
        strResult = "Error Response code "
                + response.getStatusLine().getStatusCode() + " :"
                + response.getStatusLine().toString();
        Log.i("tag", strResult);
        return null;
    }
    return strResult;
}

[/code]

有碰到类似的朋友吗?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

5条回答

为你推荐

换一换