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")); } }
getParameterXxx()methods only work for extracting query parameters of aGET, and form post parameters of aPOST, i.e. whenContent-Typeisapplication/x-www-form-urlencoded. Since your content type isapplication/json, they return nothing, as they should. CallgetReader()to read your JSON data.