我正在使用以下代码调用Web服务:
protected Boolean doInBackground(Void... params) {
int resCode;
String uri = "http://myServer:8080/api/activities/post";
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/json");
request.setHeader("Accept","application/json");
try{
JSONStringer requestData = new JSONStringer()
.object()
.key("codeActivity").value("XLT-900")
.key("firstValue").value("9")
.key("secondValue").value("3")
.endObject();
StringEntity entity = new StringEntity(requestData.toString());
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
resCode = response.getStatusLine().getStatusCode();
if (resCode == 200) {
return true;
}else{
Log.i("doInBackground","resCode: "+resCode);
return false;
}
}catch(Exception ex){
ex.printStackTrace();
return false;
}
}
应发送的json数据是(我已经验证已正确创建):
{"codeActivity":"XLT-900","firstValue":"9","secondValue":"3"}
但我总是得到结果: 400:请求不好
但是如果我从POSTMAN或其他类似的应用程序调用相同的ws,我获得状态200: Ok
,以确保ws很好。
那么错误在哪里?
答案 0 :(得分:0)
试试这个:
StringEntity se = new StringEntity(requestData.toString(), "UTF-8");
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));