如何从HttpClient帖子发送的另一个servlet中读取参数?

时间:2014-07-14 07:53:30

标签: java servlets httpclient

我必须使用从一个servlet到另一个servlet的HttpClient帖子......

CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(
        "http://localhost:8080/FitsServlets/GisServlet");

post.setHeader("Referer", "http://localhost/something");
post.setHeader("Content-type", "application/json");

StringEntity params=new StringEntity("test..");

post.setEntity(params);
HttpResponse responseGis = client.execute(post);

我想读取从另一个servlet收到的参数,但它不起作用。这是接收帖子并需要读取params的servlet的代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    System.out.println("gis..");

    Enumeration<String> parameterNames = request.getParameterNames();

    while (parameterNames.hasMoreElements()) {

        String paramName = parameterNames.nextElement();
        System.out.println("name:" + paramName);
        String[] paramValues = request.getParameterValues(paramName);

        for (int i = 0; i < paramValues.length; i++) {

            String paramValue = paramValues[i];
            System.out.println("value: " + paramValue);
        }
    }
}

有人能帮助我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

实际上,我认为您正在尝试将请求有效负载读取为请求参数。

由于您要将String作为实体发送到第二个Servlet,因此您应该打开一个代表您InputStream的请求的流链并提取内容:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
  // Do whatever you want here...
  InputStream is = request.getInputStream();      
  if (is != null) {
    StringBuilder sb = new StringBuilder();
    String line;
    try {
        BufferedReader reader = 
          new BufferedReader(new InputStreamReader(is, "UTF-8"));
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    } finally {
        is.close();
    }
    System.out.println(sb.toString());
  }
  //...
}