2016-05-11 10 views
0

Java HttpServletでは、必ずしも転送する必要はなく、元のリクエストのヘッダー情報を使用して別のローカルサービスからデータを要求できますか?Javaサーブレットローカルサービスからのデータ要求

例えば、私は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でハンドラの変更を行うと、物事の適性性が変わります。あなたはHTTPリクエストを作成するには、私のこの回答を使用することができます

+2

新しいHttpGetを作成し、元の要求のヘッダー情報を入力し、http:// localhost/foo/bazに送信しますか? –

答えて

0

ヘッダーに元のリクエストのプロパティを含めるには、HTTPリクエストからBufferedReaderを取得できました。

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

send get request

加えて、いくつかの注意を払ってリクエストヘッダをコピーする必要があるかもしれない: HttpURLConnectionと変更を使用して

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

ヘッダーの特定のプロパティをコピーするだけで済みます。しかし、私は質問があります: 'HttpURLConnection'とは異なる' GET'リクエストを行う 'HttpGet'と' HttpClient'メソッドはどうですか?ここで私の解決策を投稿しますが、それは私が思いついたものです。 – Aetylus

+1

@Aetylus - リクエスト/レスポンスの本体を処理するための追加機能を提供するため、Apache HTTPコンポーネントのクラスを使用しました。おそらく 'HttpsUrlConnection'であなたの仕事には十分です。私の答えにメソッド 'setProxySpecificRequestHeaders()'のコードを追加します。 – JimHawkins

関連する問題