HttpClient filter中间转发从A tomcat转发至B tomcat
BackFilter.java
主要解决基于HttpGet/HttpPost以及基于HttpPost的附件流转发
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; 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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.http.Header;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver; import com.xinhe99.utils.DateUtil; public class BackFilter implements Filter{ public void destroy() { } public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("--------------filter--------------------------");
HttpServletRequest request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) res; request.setCharacterEncoding(HttpClientBack.encodeUTF);
Map<String, String> params = new HashMap<String, String>();
String method = request.getMethod(); //获取提交类型
String IP = getRemoteHost(request); //获取真实Ip
String requestURI = request.getRequestURI();//获取请求URI
System.out.println(request.getRequestURI());
System.out.println(request.getRequestURL());
System.out.println(request.getQueryString());
String scheme = request.getScheme(); //获取协议名称(http或https)
String realName = "10.168.110.247:8080"; //读取的域名
String strUr="://";
String url=scheme + strUr + realName + requestURI;
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()){
String key = parameterNames.nextElement();
String value = request.getParameter(key);
params.put(key, value);
} byte[]b=new byte[1024];
ResponseResult result = null;
// if("post".equalsIgnoreCase(method)){
// b = HttpClientBack.post(url, params,IP);
// }
// if("get".equalsIgnoreCase(method)){
// b= HttpClientBack.get(url,IP);
// } if("post".equalsIgnoreCase(method)){
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
InputStream in = null;
if (multipartResolver.isMultipart(request)) {
System.out.println("wenjian============");
MultipartHttpServletRequest mreqest = multipartResolver
.resolveMultipart(request);
Map<String, MultipartFile> filesMap = mreqest.getFileMap();
Collection<MultipartFile> fileList = filesMap.values();
for (MultipartFile mf : fileList) {
//获取原始文件名
String originalFilename =mf.getOriginalFilename();
//获取文件流,可以进行处理
in = mf.getInputStream();
result = HttpClientBack.postMuti(url, params, IP,originalFilename,in); }
}else
{
result = HttpClientBack.post(url, params,IP);
}
}
if("get".equalsIgnoreCase(method)){
// add query string
if(null != request.getQueryString()){
url += "?" + request.getQueryString();
}
result= HttpClientBack.get(url,IP);
} if(null != result){
b = result.getBody();
}else{
///do you wangcan beibei xietong chuli
}
//文件名用日期加时间戳
String filename=DateUtil.getDate(new Date()).replaceAll("-", "")+String.valueOf(new Date().getTime());
//设置相应头
Header[] headers = result.getHeaders();
if(null != headers && 0 < headers.length){
for(Header header : headers){
response.setHeader(header.getName(), header.getValue());
}
}
// response.setHeader("Content-type", "application/xls;charset=UTF-8");
// response.setContentType("application/x-msdownload");
// response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls;charset=UTF-8"); if(b.length !=-1){
response.getOutputStream().write(b);
}else{
response.getOutputStream().write(-1);
} } public void init(FilterConfig arg0) throws ServletException { } public String getRemoteHost(javax.servlet.http.HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
}
return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
} public String getUrl() {
Properties props = new Properties(); InputStream in = BackFilter.class.getResourceAsStream("/config/config.properties"); try {
props.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 读取特定属性
String key = "target.url";
String url = props.getProperty(key);
return url;
} }
HttpClientBack.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set; import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.Args;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.apache.xmlbeans.impl.common.IOUtil; public class HttpClientBack { public static final String encodeUTF = "UTF-8"; // 发送post请求
public static ResponseResult post(String url, Map<String, String> params,
String ip) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
byte[] body = new byte[1024]; // body = invoke(httpclient, post,ip); ResponseResult result = null;
try {
HttpPost post = postForm(url, params);
// HttpGet get = new HttpGet(url);
result = invoke(httpclient, post, ip);
httpclient.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
} // try {
// httpclient.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// return body;
} // 发送get请求
public static ResponseResult get(String url, String ip) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
// byte[] body = new byte[1024];
ResponseResult result = null;
try {
HttpGet get = new HttpGet(url);
result = invoke(httpclient, get, ip);
httpclient.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
} // return body;
} // 执行
private static ResponseResult invoke(CloseableHttpClient httpclient,
HttpUriRequest httpost, String ip) { httpost.setHeader("x-forwarded-for_new", ip);
HttpResponse response = sendRequest(httpclient, httpost);
return new ResponseResult(paseResponse(response),
response.getAllHeaders());
} // 解析
private static byte[] paseResponse(HttpResponse response) {
HttpEntity entity = response.getEntity(); byte[] body = null;
try { body = EntityUtils.toByteArray(entity);
} catch (Exception e) {
e.printStackTrace();
} return body;
} // 正式发送
private static HttpResponse sendRequest(CloseableHttpClient httpclient,
HttpUriRequest httpost) {
HttpResponse response = null; try {
response = httpclient.execute(httpost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
} // post方式获取并包装参数
private static HttpPost postForm(String url, Map<String, String> params) { HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>(); Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
} try {
httpost.setEntity(new UrlEncodedFormEntity(nvps,
HttpClientBack.encodeUTF));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return httpost;
}
/**
* 处理附件上传
* @param url
* @param params
* @param ip
* @param fileName
* @param targetIn
* @return
*/
public static ResponseResult postMuti(String url,
Map<String, String> params, String ip, String fileName,
InputStream targetIn) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig).build(); ResponseResult result = new ResponseResult();
InputStream localIn = targetIn;
HttpEntity reqEntity = null;
InputStream responseIn = null;
CloseableHttpResponse response = null;
byte[] datas =null;
try {
HttpPost httpPost = postForm(url, params);
httpPost.setHeader("x-forwarded-for_new", ip);
InputStreamBody bin = new InputStreamBody(targetIn, fileName);
StringBody uploadFileName = new StringBody(fileName,
ContentType.create("text/plain", Consts.UTF_8));
// 以浏览器兼容模式运行,防止文件名乱码。
reqEntity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", bin).addPart("filename", uploadFileName)
.setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(reqEntity);
System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
// 发起请求 并返回请求的响应
response = httpClient.execute(httpPost);
responseIn = response.getEntity().getContent();
datas = toByteArray(responseIn);
// 打印响应状态
System.out.println(response.getStatusLine());
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印响应长度
System.out.println("Response content length: "
+ resEntity.getContentLength());
// 打印响应内容
System.out.println(new String(datas,Charset.forName("UTF-8")));
}
// 销毁
//EntityUtils.consume(resEntity);
result.setBody(datas);
result.setHeaders(response.getAllHeaders());
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
try {
if (response != null) {
response.close();
}
if (localIn != null) {
localIn.close();
}
if (responseIn != null) {
responseIn.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
private static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try{
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
}finally{
if(output!=null){
output.close();
}
}
return output.toByteArray();
}
}
HttpClient filter中间转发从A tomcat转发至B tomcat的更多相关文章
- Apache 实现ProxyPass转发URL到Tomcat并实现http自动转https【转载】
转自 Apache 实现ProxyPass转发URL到Tomcat并实现http自动转https - OPEN 开发经验库http://www.open-open.com/lib/view/open1 ...
- 通过一个tomcat端口访问多个tomcat项目 tomcat转发
需求是这样的,有一个tomcat,是80端口,现在我要通过这个tomcat转发到服务器其他tomcat,其他tomcat的端口不是80.这样做就可以避免这样www.baidu.com:8081的情况. ...
- Tomcat是什么:Tomcat与Java技、Tomcat与Web应用以及Tomcat基本框架及相关配置
1.Tomcat是什么 Apache Tomcat是由Apache Software Foundation(ASF)开发的一个开源Java WEB应用服务器. 类似功能的还有:Jetty. ...
- Tomcat请求处理过程(Tomcat源代码解析五)
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/ ...
- springboot放到linux启动报错:The temporary upload location [/tmp/tomcat.8524616412347407692.8111/work/Tomcat/localhost/ROOT/asset] is not valid
1.背景 笔者的springboot在一个非root用户环境下运行,这种环境下可以保证不被潜在的jar/开源框架漏洞提权. 比如在防火墙上把外网访问来的443端口映射到本地8443的java web端 ...
- Tomcat目录结构及Tomcat Server处理一个http请求的过程
http://blog.sina.com.cn/s/blog_62cb15980101jh9x.html 1.Tomcat的结构概述 Tomcat服务器是由一系列可配置的组件构成,其核心组件是 ...
- How Tomcat works — 四、tomcat启动(3)
上一节说到StandardService负责启动其子组件:container和connector,不过注意,是有先后顺序的,先启动container,再启动connector,这一节先来看看conta ...
- Tomcat配置(二):tomcat配置文件server.xml详解和部署简介
*/ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...
- Tomcat(五):nginx/httpd + tomcat及负载均衡tomcat
*/ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...
随机推荐
- tomcat 错误查看
路径 : \tomcat\logs 清除日志,重新启动生成 从上到下,依次查看错误,可以看到,上面的两个是系统的启动模块.然后第三行错误提示,明显指出了错误原因 “NoClassDefFoundErr ...
- HTML 布局
网站布局 大多数网站会把内容安排到多个列中(就像杂志或报纸那样). 大多数网站可以使用 <div> 或者 <table> 元素来创建多列.CSS 用于对元素进行定位,或者为页面 ...
- OGG学习笔记03-单向复制简单故障处理
OGG学习笔记03-单向复制简单故障处理 环境:参考:OGG学习笔记02-单向复制配置实例 实验目的:了解OGG简单故障的基本处理思路. 1. 故障现象 故障现象:启动OGG源端的extract进程, ...
- jQuery Deferred和Promise的使用介绍:
deferred对象是从jquery1.5.0引入的一个新对象,ES6也引入了Promise的正式规范. 抽象来说,deferreds 可以理解为表示需要长时间才能完成的耗时操作的一种方式,相比于阻塞 ...
- 为什么python适合写爬虫?(python到底有啥好的?!)
我用c#,java都写过爬虫.区别不大,原理就是利用好正则表达式.只不过是平台问题.后来了解到很多爬虫都是用python写的.因为目前对python并不熟,所以也不知道这是为什么.百度了下结果: 1) ...
- bootstropt-table 大量字段整体表单上传之时间处理
js 中用$('#addUserForm').serialize(),//获取表单中所有数据 传送到前台 (controller) $.ajax({ type : "POST", ...
- vue-router跳转页面
小结放在前:先祝大家新年快乐!鸡年大吉大利!在新的一年里大家都有跳跃般的成长!作为新年的第一篇文章,就拿他来给大家拜个年!!!文章前部份讲解了vue-router路由的配置,后半部分为去年的文章vue ...
- qmake的配置功能(Configuration Features)
Configuration Features qmake can be set up with extra configuration features that are specified in f ...
- C++源码的调用图生成
前言 之前受知乎用户mailto1587启发,写了个C++源码的调用图生成器,可以以图示法显示C++函数的调用关系, 代码放在了github仓库里,仅供参考: CodeSnippet/python/S ...
- find查找命令
find # 格式 find [路径] [参数] [表达式] -exec 指令 {} \ ; -{} 代表find找到的文件 -\ 禁止转意 : 表示本行指令结束 # find /sbin -type ...