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的更多相关文章

  1. Apache 实现ProxyPass转发URL到Tomcat并实现http自动转https【转载】

    转自 Apache 实现ProxyPass转发URL到Tomcat并实现http自动转https - OPEN 开发经验库http://www.open-open.com/lib/view/open1 ...

  2. 通过一个tomcat端口访问多个tomcat项目 tomcat转发

    需求是这样的,有一个tomcat,是80端口,现在我要通过这个tomcat转发到服务器其他tomcat,其他tomcat的端口不是80.这样做就可以避免这样www.baidu.com:8081的情况. ...

  3. Tomcat是什么:Tomcat与Java技、Tomcat与Web应用以及Tomcat基本框架及相关配置

    1.Tomcat是什么       Apache Tomcat是由Apache Software Foundation(ASF)开发的一个开源Java WEB应用服务器. 类似功能的还有:Jetty. ...

  4. Tomcat请求处理过程(Tomcat源代码解析五)

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/ ...

  5. 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端 ...

  6. Tomcat目录结构及Tomcat Server处理一个http请求的过程

    http://blog.sina.com.cn/s/blog_62cb15980101jh9x.html 1.Tomcat的结构概述     Tomcat服务器是由一系列可配置的组件构成,其核心组件是 ...

  7. How Tomcat works — 四、tomcat启动(3)

    上一节说到StandardService负责启动其子组件:container和connector,不过注意,是有先后顺序的,先启动container,再启动connector,这一节先来看看conta ...

  8. Tomcat配置(二):tomcat配置文件server.xml详解和部署简介

    */ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...

  9. Tomcat(五):nginx/httpd + tomcat及负载均衡tomcat

    */ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...

随机推荐

  1. QT移植

    QT下载地址:http://download.qt.io/archive/qt/1.编译tslib(touch screen lib) 准备工作:确保以下工具安装完成 sudo apt-get ins ...

  2. 天兔(Lepus)监控邮件推送安装配置

    好吧,我承认官网的邮件配置教程我又没看懂,这里记录下我的配置方法 [root@HE3]# vi /usr/local/lepus/test_send_mail.py #!/usr/bin/envpyt ...

  3. Java中的集合类型的继承关系图

    Java中的集合类型的继承关系图

  4. AngularJS的五个超酷特性

    AngularJS是一个超棒的javascript框架,不单单对于开发人员来说非常有吸引力,对于UI设计师来说也同样出色.在这篇教程中,我们将简单的介绍AngularJS几个重量级必备特性,并且介绍它 ...

  5. Socket通信流程

    Socket通信流程 HTTP 底层就是通过socket建立连接通信管道,实现数据传输 HTTP是一个TCP的传输协议(方式),它是一个可靠,安全的协议

  6. [2017.02.04] C++学习记录(1)

    编编程语言的目的是帮助程序员以代码的形式表述ideas.编程语言一方面为程序员提供一组关于可以做什么的抽象,另一方面为程序员提供可以被机器执行的轮子.C++编程语言,支持4种编程范式:过程式(Proc ...

  7. 从jvm的角度来看java的多线程

    最近在学习jvm,发现随着对虚拟机底层的了解,对java的多线程也有了全新的认识,原来一个小小的synchronized关键字里别有洞天.决定把自己关于java多线程的所学整理成一篇文章,从最基础的为 ...

  8. W3Cschool学习笔记——XHTML基础教程

    XHTML 是更严格更纯净的 HTML 代码. XHTML 是什么? XHTML 指可扩展超文本标签语言(EXtensible HyperText Markup Language). XHTML 的目 ...

  9. JS 与 OC

    做项目需要从网页点击跳转到app的一个页面上,并且需要获取参数. 当时后台给写的参数是这样的.自己打开浏览器看的源码 JavaScript:window.location.href=   这句话在js ...

  10. iOS Storyboard适配问题

      通用的Storyboard 通用的stroyboard文件是通向自适应布局光明大道的第一步.在一个storyboard文件中适配iPad和iPhone的布局在iOS8中已不再是梦想.我们不必再为不 ...