来自InputStreamEntity的HttpEntityEnclosingRequest setEntity获取参数名称错误

时间:2014-10-16 23:00:14

标签: java post parameters proxy apache-httpclient-4.x

我正在将代理服务器编写为servlet。我正在使用HttpClient作为代理客户端。当我收到带有正文的POST请求时,我试图使用InputStreamEntity将正文复制到重写的代理请求中。目标servlet无法找到参数。调试后,似乎用数组表示法重命名参数:例如,“name”变为“name [0]”。

以下是代码:

    // Create the actual proxy request.
String proxyRequestUri =
  rewriteUrlFromRequest(servletRequest, target, null);
HttpRequest proxyRequest = null;
if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
    || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
  HttpEntityEnclosingRequest eProxyRequest =
    new BasicHttpEntityEnclosingRequest(servletRequest.getMethod(),
                                        proxyRequestUri);

    // Copy the entity from the request body.
    eProxyRequest.setEntity(new InputStreamEntity(servletRequest.getInputStream(),
                                                  servletRequest.getContentLength()));
  // Set the enclosing request into the request to return.
  proxyRequest = eProxyRequest;
} else {
  // No message body, just create a basic request.
  proxyRequest =
    new BasicHttpRequest(servletRequest.getMethod(), proxyRequestUri);
}
return proxyRequest;

我通过从请求中获取参数映射并将其转储来验证名称是否正确,一切看起来都很好。代理目标服务器上的相同转储显示附加了“[0]”的名称,因此该代码中的字符串比较无法找到参数。

我用这段代码替换了上面的代码,它将地图中的参数复制到一个新的表格编码实体中,并且工作正常:

    // Create the actual proxy request.
String proxyRequestUri =
  rewriteUrlFromRequest(servletRequest, target, null);
HttpRequest proxyRequest = null;
if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
    || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
  HttpEntityEnclosingRequest eProxyRequest =
    new BasicHttpEntityEnclosingRequest(servletRequest.getMethod(),
                                        proxyRequestUri);

  if (servletRequest.getContentType().equals("application/x-www-form-urlencoded")) {
    // Extract the parameter map and create a new form entity.
    Map<String, String[]> map = servletRequest.getParameterMap();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    for (String name : map.keySet()) {
      String[] array = map.get(name);
      for (int i = 0; i < array.length; i++) {
        nameValuePairs.add(new BasicNameValuePair(name, array[i]));
      }
    }
    eProxyRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  } else {
    // Copy the entity from the request body.
    eProxyRequest.setEntity(new InputStreamEntity(servletRequest.getInputStream(),
                                                  servletRequest.getContentLength()));
  }
  // Set the enclosing request into the request to return.
  proxyRequest = eProxyRequest;
} else {
  // No message body, just create a basic request.
  proxyRequest =
    new BasicHttpRequest(servletRequest.getMethod(), proxyRequestUri);
}
return proxyRequest;

我认为这种解决方法不够通用,无法处理所有可能的事情,所以如果可以的话,我想解决原来的问题。

0 个答案:

没有答案