Java Servlet从本地服务请求数据

时间:2016-05-11 19:50:59

标签: java servlets

在Java HttpServlet中,是否可以使用原始请求的标头信息从其他本地服务请求数据而不必转发?

例如,我有FooBar.java

// Handles the url at /foo/bar and can be accessed at http://localhost/foo/bar
public class FooBar extends HttpServlet
{
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      Object data = ...                             // 1. Retrieve data at http://localhost/foo/baz utilizing the current request's header
      Object newData = doSomething(data);           // 2. Process the data
      response.getWriter().write(newData.toString); // 3. Return the processed data
   }

   private Object doSomething(Object data)
   {
      // Perform some business logic
   }
}

第1步是这里的问题。这样做的目的是我希望能够在完全返回数据之前对数据执行某种逻辑,但不一定有访问权限确实对/foo/baz处理程序的更改做了适当的处理事物的本质。

2 个答案:

答案 0 :(得分:1)

您可以使用我的这个答案来创建HTTP请求:send get request

此外,可能需要谨慎复制请求标头:

private static final Set forbiddenCopyHeaders = new HashSet<>(Arrays.asList(new String[]{
        "connection"
        , "transfer-encoding"
        , "content-length"    // POST kann zu Status 500 führen, wenn die content-length kopiert wird
        , "via"
        , "x-forwarded-for"
        , "x-forwarded-host"
        , "x-forwarded-server"
}));

private void copyRequestHeaders(HttpServletRequest customerRequest, HttpRequestBase internRequest) throws
        HttpException
{

    Enumeration<String> headerNames = customerRequest.getHeaderNames();
    String connectionHeader = customerRequest.getHeader("connection");

    while (headerNames.hasMoreElements())
    {
        String headerName = headerNames.nextElement();

        boolean copyAllowed = !forbiddenCopyHeaders.contains(headerName.toLowerCase()) &&
                !StringUtils.containsIgnoreCase(connectionHeader, headerName);

        if (copyAllowed)
        {
            Enumeration<String> values = customerRequest.getHeaders(headerName);
            while (values.hasMoreElements())
            {
                internRequest.addHeader(headerName, values.nextElement());
            }
        }
    }

    setProxySpecificRequestHeaders(customerRequest, internRequest);
}


private void setProxySpecificRequestHeaders(HttpServletRequest customerRequest,
                                            HttpRequestBase internRequest) throws HttpException
{
    String serverHostName = "doorman";
    try
    {
        serverHostName = InetAddress.getLocalHost().getHostName();
    }
    catch (UnknownHostException e)
    {
        logger.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e);
    }

    String originalVia = customerRequest.getHeader("via");
    StringBuilder via = new StringBuilder("");
    if (originalVia != null)
    {
        if (originalVia.contains(serverHostName))
        {
            logger.error("This proxy has already handled the Request, will abort.");
            throw new HttpException("Request has a cyclic dependency on this proxy.");
        }
        else
        {
            via.append(originalVia).append(", ");
        }
    }
    via.append(customerRequest.getProtocol()).append(" ").append(serverHostName);

    internRequest.addHeader("via", via.toString());
    internRequest.addHeader("x-forwarded-for", customerRequest.getRemoteAddr());
    internRequest.addHeader("x-forwarded-host", customerRequest.getServerName());
    internRequest.addHeader("x-forwarded-server", serverHostName);

    internRequest.addHeader("accept-encoding", "");
}

答案 1 :(得分:0)

使用BufferedReader并更改标头以包含原始请求中的属性,我能够从HTTP请求中获取public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Step 1 String serverName = request.getLocalName(); String contextPath = request.getContextPath(); URL url = new URL("https://" + serverName + contextPath + "/baz"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Key Header", request.getHeader("Key Header")); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Step 2 ... // Do something with the data from the reader // Step 3 ... // Write the data back using the response }

{{1}}