0

Here I am posting the JSON data using HttpClient. But I am not able to read the data on the other application. When I do request.getParameter("username"), it returns me null. Both my applications are deployed on the same server. Please tell me what I am doing wrong. Thank you

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpPost postRequest = new HttpPost("http://localhost:8080/AuthenticationService/UserIdentificationServlet");
        postRequest.setHeader("Content-type", "application/json");

        StringEntity input = new StringEntity("{\"username\":\""+username+"\"}");
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse postResponse = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((postResponse.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    }
Raunak Agarwal
  • 6,637
  • 6
  • 34
  • 60
  • You need to understand the difference between [application/x-www-form-urlencoded](http://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data) ie form request parameters (`HttpServletRequest#getParameter()`) and having `application/json` which has a request body of `json` (`HttpServletRequest#getInputStream()`). – Adam Gent Feb 16 '13 at 05:13

1 Answers1

1

If you want to use request.getParameter, then you have to post the data in a URL encoded format.

//this example from apache httpcomponents doc
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);
almalki
  • 3,997
  • 22
  • 29