I try to send directly a JSON string with HttpClient 4.4 in an application (SWT/JFace) :
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;
}
I try to get the response from the server (Apache/PHP) with $POST
the correct content of $POST
should be :
array("mail"=>"admin@localhost","password"=>"xyz")
When I use content-type : application/x-www-form-urlencoded
$POST
content is :
array( "{"mail":"admin@localhost","password":"xyz"}"=> )
When I use content-type : application/json
$POST
is empty : array()
Is there a way to post the JSON string with HttpClient or should I use an ArrayList<NameValuePair>
and add each member of my object in the entity ?