1.写的一个简单的例子
package forword; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; @WebFilter("/*") public class ProxyFilter implements Filter { public ProxyFilter() { } public void destroy() { } public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain1) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) request1; HttpServletResponse response = (HttpServletResponse) response1; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String basePath = request.getScheme() + "://" + "127.0.0.1:9080"; String locationUrl = basePath + request.getRequestURI(); String queryValue = request.getQueryString(); if (StringUtils.isNotBlank(queryValue)) { locationUrl += "?" + queryValue; } IOUtils.write(HttpUtils.sendGet(locationUrl, request), response.getOutputStream()); } public void init(FilterConfig fConfig) throws ServletException { } @SuppressWarnings("unused") private String solveUrl(HttpServletRequest request) { return request.getRequestURI().replaceAll(request.getContextPath(), ""); } public static void main(String[] args) { } }
思路如下:
1.首先所以的请求都必须要经过代理服务器,有代理服务器根据相应的规则(自定义),选择合适的目标服务器进行转发,
2.转发的实现,我们可以自己去创建HttpURLConnection 连接到目标服务器获取数据,也可以采用成熟的httpclient 去请求数据
3.将数据响应回去.
实现难点: 苦难的地方主要是在对http协议的解析,在这里我使用了httpclient 来屏蔽这些底层的实现,但是我们自己应该懂得如何解析http请求
解析请求的例子:
public class ParseUtils { public static byte[] readLine(InputStream in) throws IOException { ByteAppender appender = new ByteAppender(); int _data = -1; while(true) { int data = in.read(); if(data == -1) break; if(_data == ‘\r‘) { if(data == ‘\n‘) break; else { appender.append((byte)_data); appender.append((byte)data); } } if(data != ‘\r‘) { appender.append((byte) data); } _data = data; } return appender.getDatas(); } }
//解析传递过来的报文
private void parse_(Socket socket) throws IOException { InputStream in = socket.getInputStream(); byte[] firstLine = ParseUtils.readLine(in); if(firstLine.length == 0) { throw new HttpException("heart-beaten test from client side"); } messageHeader = new String(firstLine); parseHeaders(in); bodyInput = in; InetAddress address = socket.getInetAddress(); setClientHost(address.getHostAddress()); }