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