如何从POST Url获取服务器上的参数

时间:2013-12-11 00:03:21

标签: java jsp java-ee servlets

我正在尝试使用Post Method从客户端使用“NameValuePair”格式的某些数据来访问某些URL,并从servlet(服务器端)的URL接收该数据以执行某些计算并将响应发送回客户端在JSON fromat。

但是我能够在Servlet(服务器)上找到正确的数据

从客户端点击网址

private void sendHTTPSPost() throws Exception {

    String url = "http://localhost:8080/test/Registration";
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("name", "A"));
    urlParameters.add(new BasicNameValuePair("age", "12"));
    urlParameters.add(new BasicNameValuePair("sex", "M"));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    System.out.println("Response Code : " + 
                                response.getStatusLine().getStatusCode());
    BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

    StringBuilder result = new StringBuilder();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    System.out.println(result.toString());

}

在Servlet上

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);   
    Enumeration headerNames = request.getHeaderNames();

    while(headerNames.hasMoreElements()) {
       String paramName = (String)headerNames.nextElement();
       System.out.println("Value of param  is ------------------"+paramName);
       String paramValue = request.getHeader(paramName);
       System.out.println("Value of key is ------------------"+paramValue);
  }

}

我尝试了很多但没有得到正确的结果。

3 个答案:

答案 0 :(得分:0)

你错过了

post.setRequestHeader("Content-Type",
    "application/x-www-form-urlencoded");

答案 1 :(得分:0)

您正在从请求中获取标头,您必须使用request.getParameterNames()来获取参数。

答案 2 :(得分:0)

您可以使用 -

requests.getParameter(&#34;名称&#34); //返回A

requests.getParameter(&#34;年龄&#34); //返回12

requests.getParameter(&#34;性别&#34); //返回M