您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection 实现代理。

2015-11-03 11:53 501 查看
public class ForwardProxyController extends AbstractController {
private String sourceContextPath;
private String targetContextHostUrl;

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws IOException {
Logger.info(this, "request : " + request.getPathInfo());
try {
HttpURLConnection connection = parse(request);
response.setContentType(connection.getHeaderField("Content-Type"));
IOUtils.copy(connection.getInputStream(), response.getOutputStream());
}catch (Exception e) {
response.getOutputStream().write("".getBytes());
}

return null;
}

private HttpURLConnection parse(HttpServletRequest request) throws IOException {
Logger.info(this, "request : " + request.getRequestURI());
String requestString = request.getRequestURI().replace(sourceContextPath, "");
String queryString = request.getQueryString();
String uri = targetContextHostUrl + requestString;
if(StringUtils.isNotBlank(queryString)){
uri = uri + "?" + queryString;
}

Logger.info(this, "target uri : " + uri);
HttpURLConnection connection =  (HttpURLConnection) new URL(uri).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod(request.getMethod());
connection.setRequestProperty("Content-type", request.getContentType());
connection.setRequestProperty("contentType", "utf-8");

IOUtils.copy(request.getInputStream(), connection.getOutputStream());

return connection;
}
}


<bean id="reverseProxyController" class="com.lufax.operation.gw.ForwardProxyController" >
<property name="sourceContextPath" value="${OPERATION_GW_CONTENT_PATH}" />
<property name="targetContextHostUrl" value="${OPERATION_APP_HOST_URL}${OPERATION_APP_CONTENT_PATH}" />
</bean>

<bean id="forwardProxyController" class="com.lufax.operation.gw.ForwardProxyController" >
<property name="sourceContextPath" value="${OPERATION_GW_CONTENT_PATH}" />
<property name="targetContextHostUrl" value="${B_SYSTEM_HOST_URL}" />
</bean>

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/bsfront/**=forwardProxyController
/service/**=reverseProxyController
</value>
</property>
<property name="order" value="10000" />
</bean>


web.xml

<servlet>
<servlet-name>dynamic-velocity</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/operation-gw-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dynamic-velocity</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: