How can I send a regular post request with json'ом ? I just can not understand. Such a thing does not work (it works more precisely, but not json sent, but data):

 HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(stringUrl); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("id", "126927462")); params.add(new BasicNameValuePair("message", message)); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); httppost.setHeader("Content-Type", "application/json"); //Execute and get the response. HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); 

Can someone fix my code or give an example of how to send json POST'ом ?

    2 answers 2

    UrlEncodedFormEntity is probably used to send Content-Type: application/x-www-form-urlencoded . Try to replace

     List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("id", "126927462")); params.add(new BasicNameValuePair("message", message)); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); 

    on

     JSONObject obj = new JSONObject(); obj.put("id", "126927462"); obj.put("message", message); httppost.setEntity(new StringEntity(obj.toString(), "UTF-8")); 

    The code from this answer . Java I do not know, I can be mistaken.

      First you need to create JSON, for example with the jackson library :

       Map<String, String> mapForJson = new HashMap<>(); mapForJson.put("id", "126927462"); mapForJson.put("message", message); ObjectMapper mapper = new ObjectMapper(); String jsonData = mapper..writeValueAsString(mapForJson); 

      And for a post request with JSON, you can use http-request built on apache http api.

       HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class) .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build(); public void send(){ ResponseHandler<String> response = httpRequest.executeWithBody(jsonData); System.out.println(response.getStatusCode()); System.out.println(response.get()); //returns response body } 

      I strongly recommend reading the documentation before use.