2013-02-16 4 views
0

여기에서 HttpClient를 사용하여 JSON 데이터를 게시하고 있습니다. 하지만 다른 응용 프로그램의 데이터를 읽을 수 없습니다. 내가 request.getParameter("username") 일 때, 그것은 null을 돌려줍니다. 두 응용 프로그램 모두 동일한 서버에 배포됩니다. 내가 뭘 잘못하고 있는지 말해줘. 고맙습니다.Java HttpClient : 게시 요청에서 json 데이터를 읽을 수 없습니다.

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(); 
    } 
+0

당신은 [을 application/x-www-form-urlencoded 된 (http://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart 차이를 이해하는 것이 필요 ('HttpServletRequest # getParameter()'), 요청 본문이'json' ('HttpServletRequest # getInputStream()') 인'application/json'을 가지고있다. –

답변

1

request.getParameter를 사용하려면 URL 인코딩 형식으로 데이터를 게시해야합니다.

//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); 
관련 문제