Code to get a Java servlet to act as a proxy?

后端 未结 2 547
庸人自扰
庸人自扰 2021-02-04 01:12

I have two Java web applications that have a single servlet that gets mapped to a specific URL:

red.war/
    WEB-INF/classes
        com.me.myorg.red.RedServlet          


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-04 01:17

    Since there is not yet an approved answer I try to write how I see the solution to this request use apache-http-commons library. In addition I suggest to add a flush on writer.

    public class ProxyServlet extends HttpServlet {
    @Override
    public doGet(HttpServletRequest request, HttpServletResponse response) {
        String forwardingAddress;
        if(shouldBeRed(request))
            forwardingAddress = "http://red.example.com/doStuff";
        else
            forwardingAddress = "http://blue.example.com/doStuff";
    
        PrintWriter writer = response.getWriter();
    
        writer.write(getResponseFromBackend(forwardingAddress, request));
        **writer.flush();**
    }
    
    private String getResponseFromBackend(String addr, HttpServletRequest req) {
            HttpClient client = new HttpClient();
            HttpMethod method = new GetMethod(url);
            client.executeMethod(method);
            String body=method.getResponseBodyAsString();
            return body;
    
    }
    

    }

提交回复
热议问题