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();
	}
}

  

时间: 2024-10-10 17:36:32

HttpClient filter中间转发从A tomcat转发至B tomcat的相关文章

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

需求是这样的,有一个tomcat,是80端口,现在我要通过这个tomcat转发到服务器其他tomcat,其他tomcat的端口不是80.这样做就可以避免这样www.baidu.com:8081的情况. 比如我现在的域名是www.baidu.com. 我映射好域名和ip,建好了对应的子域名one.baidu.com    two.baidu.com 我现在有三个tomcat启动这,端口分别是:80 81 82 因为默认端口是80所以我可以直接www.baidu.com 访问到我的80tomcat的

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

前面已经分析完了Tomcat的启动和关闭过程,本篇就来接着分析一下Tomcat中请求的处理过程. 在开始本文之前,咋们首先来看看一个Http请求处理的过程,一般情况下是浏览器发送http请求->建立Socket连接->通过Socket读取数据->根据http协议解析数据->调用后台服务完成响应,详细的流程图如上图所示,等读者读完本篇,应该就清楚了上图所表达的意思.Tomcat既是一个HttpServer也是一个Servlet 容器,那么这里必然也涉及到如上过程,首先根据HTTP协议

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

1.Tomcat是什么       Apache Tomcat是由Apache Software Foundation(ASF)开发的一个开源Java WEB应用服务器. 类似功能的还有:Jetty.Resin.Websphere.weblogic.JBoss.Glassfish.GonAS等,它们的市场占有率如下,可以看到Tomcat是最受欢迎的Java WEB应用服务器. Tomcat在技术实现上所处的位置如下: 下面我们来了解下Tomcat与这些技术之间的关系. 1-1.Tomcat与Ja

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

上一节说到StandardService负责启动其子组件:container和connector,不过注意,是有先后顺序的,先启动container,再启动connector,这一节先来看看container. 目录 Pipeline和Vavle StandardEngine类和StandardHost类 StandardContext类 总结 Pipeline和Vavle 在第二节(How Tomcat works — 二.tomcat启动(1))中没有介绍关于Pipeline和Vavle,因

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

*/ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hljs-comment, .hljs-template_comment, .diff .hljs-header, .hljs-javadoc { color: #998; font-style: italic; } .hljs-keyword, .css .rule .hljs-keyword, .h

java.io.IOException: java.io.FileNotFoundException: /tmp/tomcat.2457258178644046891.8080/work/Tomcat/localhost/innovate-admin/C:/up/154884318438733213952/sys-error.log (没有那个文件或目录)

环境: Ubuntu18 vue+elementUI 实现文件的上传 报错信息: java.io.IOException: java.io.FileNotFoundException: /tmp/tomcat.2457258178644046891.8080/work/Tomcat/localhost/innovate-admin/C:/up/154884318438733213952/sys-error.log (没有那个文件或目录) at org.apache.catalina.core.A

关闭tomcat, 部署并启动tomcat的脚本

1 /opt/tomcat/bin/shutdown.sh 2 sleep 5 3 ps aux|grep "apache-tomcat-7.0.1" |grep -v "grep" |grep "java" |awk '{print $2}' |xargs kill -9 4 rm -f /opt/tomcat/webapps/ibank.war 5 rm -rf /opt/tomcat/webapps/ibank 6 cp -f /home/

Tomcat关闭过程(Tomcat源码解析四)

我们在Tomcat启动过程(Tomcat源代码阅读系列之三)一文中已经知道Tomcat启动以后,会启动6条线程,他们分别如下: "ajp-bio-8009-AsyncTimeout" daemon prio=5 tid=7f8738afe000 nid=0x115ad6000 waiting on condition [115ad5000] "ajp-bio-8009-Acceptor-0" daemon prio=5 tid=7f8738b05800 nid=0x

Tomcat:基于Apache+Tomcat的集群搭建

根据Tomcat的官方文档说明可以知道,使用Tomcat配置集群需要与其它Web Server配合使用才可以完成,典型的有Apache和IIS. 这里就使用Apache+Tomcat方式来完成基于Tomcat在集群配置. 软件准备 1)Apache HTTP Server: 使用百度搜索httpd-2.2.25-win32-x86-no_ssl.msi,应该可以找到很多相关的下载链接.这里也提供一个:http://vdisk.weibo.com/s/C3trk_uGGkrmc 2)Tomcat