我尝试在应用程序(SWT / JFace)中直接发送带有HttpClient 4.4的JSON字符串:
public String postJSON(String urlToRead,Object o) throws ClientProtocolException, IOException {
String result="";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost postRequest = new HttpPost(urlToRead);
postRequest.setHeader("content-type", "application/x-www-form-urlencoded");
//postRequest.setHeader("Content-type", "application/json");
//{"mail":"admin@localhost", "password":"xyz"}
String jsonString=gson.toJson(o);
StringEntity params =new StringEntity(jsonString);
params.setContentType("application/json");
params.setContentEncoding("UTF-8");
postRequest.setEntity(params);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
}finally {
httpClient.close();;
}
return result;
}
我尝试使用$POST
$POST
的正确内容应为:
array("mail"=>"admin@localhost","password"=>"xyz")
当我使用content-type : application/x-www-form-urlencoded
$POST
内容为:
array( "{"mail":"admin@localhost","password":"xyz"}"=> )
当我使用content-type : application/json
$POST
为空:array()
有没有办法用HttpClient发布JSON字符串,还是应该使用ArrayList<NameValuePair>
并在实体中添加我的对象的每个成员?
答案 0 :(得分:0)
我把“NameValuePair”解决方案(不在评论中,答案太长),但我认为StringEntity能够理解JSON,请参阅How to POST JSON request using Apache HttpClient?并在那里:HTTP POST using JSON in Java
public String postJSON(String urlToRead,Object o) throws ClientProtocolException, IOException {
String result="";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost postRequest = new HttpPost(urlToRead);
postRequest.setHeader("content-type", "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//{"mail":"admin@localhost", "password":"xyz"}
JsonElement elm= gson.toJsonTree(o);
JsonObject jsonObj=elm.getAsJsonObject();
for(Map.Entry<String, JsonElement> entry:jsonObj.entrySet()){
nameValuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().getAsString()));
}
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
}finally {
httpClient.close();;
}
return result;
}
这样,$ POST的内容是正确的:array("mail"=>"admin@localhost","password"=>"xyz")