【发布时间】:2015-03-14 02:26:08
【问题描述】:
我尝试在应用程序 (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 从服务器 (Apache/PHP) 获取响应
$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> 并将我的对象的每个成员添加到实体中?
【问题讨论】:
标签: json post httpclient