0

I'm trying to send a JSON object using httpClient, but in the DoPost, the "HttpServletRequest request" is null, it has no parameters.

also, I tried using Postman chrome app to make a post request to the same class, and it also has the empty "HttpServletRequest request".

here it is how make the request:

public void CamposPost(){ try{ HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(this.url); StringEntity postingString = new StringEntity(this.JSONObject.toString()); post.setHeader("Content-type", "application/json"); post.setEntity(postingString); HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); this.respond=responseString; } catch(Exception ex){ ex.printStackTrace(); } } 

and the following code is the DoPost code

package com.itc.polux.request; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class post extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> parameterNames = new ArrayList<String>(request.getParameterMap().keySet()); //request.getParameterNames(); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(request.getParameter("json")); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ List<String> parameterNames = new ArrayList<String>(request.getParameterMap().keySet()); //request.getParameterNames(); PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println(request.getParameter("json")); } } 
3
  • 1
    The getParameterXxx() methods only work for extracting query parameters of a GET, and form post parameters of a POST, i.e. when Content-Type is application/x-www-form-urlencoded. Since your content type is application/json, they return nothing, as they should. Call getReader() to read your JSON data. Commented Jul 2, 2016 at 23:44
  • 1
    Try read the request body stackoverflow.com/questions/14525982/…, instead you can use high level api in the backend like JAX-RS or Spring-mvc-rest, dropwizard or sparkjava. Commented Jul 2, 2016 at 23:48
  • @Andreas tyvm, that was it, I feel so dumb now... Commented Jul 3, 2016 at 0:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.