gundumw100
2013-10-28 11:06为什么使用HttpClient发送json总是返回400?
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条回答
为你推荐
- (转到)发送HTTP请求时如何控制gzip压缩?
- gzip
- http
- 1个回答
- java实现HTTP摘要认证
- java
- 2个回答
- 为什么使用HttpClient发送json总是返回400?
- httpclient
- httppost
- android
- 0个回答
- 关于httpclient4读取网站信息的问题
- it技术
- 互联网问答
- IT行业问题
- 计算机技术
- 编程语言问答
- 0个回答
- c# httpclient调用webapi获取json数据
- json
- c#
- 2个回答
换一换