我尝试使用一组JSON参数向我的服务器发送POST请求(使用Apache HTTPClient 4.5)。我已经关注了一些SO问题,但遇到了问题。
当我使用javascript控制台发送请求时,它可以正常工作!像这样:
//Using JS console, I send a POST request and it works.
$.post('/createConfigData', {
"tailSign": "A7ALE",
"active": "Y"
});
//Get back 201
当我使用 Apache HTTPClient 4.5 尝试执行上述操作时,我会返回 415不支持的媒体类型:
HttpPost httppost = new HttpPost('/createConfigData');
String jsondata = "{\"tailSign\": \"A7ALE\",\"active\": \"Y\"}";
StringEntity jsonparam = new StringEntity(jsondata);
jsonparam.setContentType("application/json;charset=utf-8");
jsonparam.setChunked(true);
httppost.addHeader("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
httppost.setEntity(jsonparam);
httpresponse = httpclient.execute(target, httppost);
我从工作请求获得的数据是:
"*/*"
我对设置内容类型的位置感到有点困惑,无论是实体还是 httppost
=======================
将 httpost' 内容类型设置为 json ,可以 400
HttpPost httppost = new HttpPost('/createConfigData');
String jsondata = "{\"tailSign\": \"A7ALE\",\"active\": \"Y\"}";
StringEntity jsonparam = new StringEntity(jsondata);
jsonparam.setChunked(true);
httppost.addHeader("content-type", "application/json;charset=UTF-8");
httppost.setEntity(jsonparam);
httpresponse = httpclient.execute(target, httppost);
将 httpost 内容类型设置为 x-www-form-urlencoded ,可以 415
HttpPost httppost = new HttpPost('/createConfigData');
String jsondata = "{\"tailSign\": \"A7ALE\",\"active\": \"Y\"}";
StringEntity jsonparam = new StringEntity(jsondata);
jsonparam.setChunked(true);
httppost.addHeader("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
httppost.setEntity(jsonparam);
httpresponse = httpclient.execute(target, httppost);
我也尝试添加这一行:
httppost.addHeader("Accept", "*/*");
==================
使用 wireshark 我能够发现有一条错误消息与400错误请求一起出现!这只是我的JSON不正确。
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 19 Oct 2016 21:33:25 GMT
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
{"code":400,"message":"Field ConfigName is Null, Invalid Value for Seat Count, Missing counts for DSU, ICMT, SVDU, TPMU, Login user details not found, Please enter valid lruData","fleetData":{"airlineData":null,"dimAircraftJson":null,"configData":null}}
答案 0 :(得分:2)
您获得 415不支持的媒体类型,因为您已将内容类型标头覆盖为 application / x-www-form-urlencoded;字符集= UTF-8 即可。只需将其更改为:
HttpPost httppost = new HttpPost('/createConfigData');
String jsondata = "{\"tailSign\": \"A7ALE\",\"active\": \"Y\"}";
StringEntity jsonparam = new StringEntity(jsondata);
jsonparam.setChunked(true);
httppost.addHeader("content-type", "application/json;charset=UTF-8");
httppost.setEntity(jsonparam);
httpresponse = httpclient.execute(target, httppost);