package com.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.concurrent.CountDownLatch; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.DefaultHttpAsyncClient; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.log4j.Logger; /** * 标题: WebsConnByHttpClient 说明: 通过HttpClient 或 HttpAsyncClient 的 servlet或者Action * 之间的信息连接业务类 2013.03.14 NAME: wangchanglin * * 修改信息 修改日期 修改者 修改ID 修改内容 */ public class WebserviceAssistant { private static final Logger logger = Logger.getLogger(WebserviceAssistant.class); /** * Webs间的接口调用 * * @param wsURL * 用HttpClient所需的URL参数 * @return restult 业务处理结果 * @throws IOException **/ public static String getResultByHttpClient(String wsURL) throws IOException { HttpClient httpclient = new HttpClient(); GetMethod httpget = new GetMethod(wsURL); httpget.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { httpclient.executeMethod(httpget); String result = httpget.getResponseBodyAsString(); return result; } finally { httpget.releaseConnection(); } } /** * 通过HttpClient接口获取布尔结果 * * @param reqURL * @throws HttpException * @throws IOException * @return true false */ public static boolean getHttpClientBoolean(String reqURL) throws IOException { // 构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // 创建GET方法的实例 GetMethod getMethod = new GetMethod(reqURL); // 使用系统提供的默认的恢复策略 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { // 执行getMethod httpClient.executeMethod(getMethod); // 读取内容 String result = getMethod.getResponseBodyAsString(); return new Boolean(result); } finally { // 释放连接 getMethod.releaseConnection(); } } /** * Webs间的接口调用 * * @param wsURL * 用HttpClient所需的URL参数 * @return restult 业务处理结果 * @throws IOException **/ public static String getResultByHttpClientThrowTimeOut(String wsURL) throws IOException { HttpClient httpclient = new HttpClient(); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(3000); httpclient.getHttpConnectionManager().getParams().setSoTimeout(7000); GetMethod httpget = new GetMethod(wsURL); httpget.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { httpclient.executeMethod(httpget); String result = httpget.getResponseBodyAsString(); return result; } catch (IOException e) { logger.error(e); throw e; } finally { httpget.releaseConnection(); } } /** * Webs间的接口调用 HttpClient 的异步调用实现 * * @param wsURL * 用HttpClient所需的URL参数 * @throws IOException * @throws InterruptedException **/ public static void getResultAsynByHttpClient(String wsURL) throws IOException, InterruptedException { HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.start(); HttpGet[] requests = new HttpGet[] { new HttpGet(wsURL), }; final CountDownLatch latch = new CountDownLatch(requests.length); try { for (final HttpGet request : requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); } @Override public void failed(final Exception ex) { latch.countDown(); ex.printStackTrace(); } @Override public void cancelled() { latch.countDown(); } }); } } finally { latch.await(); httpclient.shutdown(); } } /** * 获取客户端真实IP<br/> * 解决多重转发获取假IP问题 * * @param request * HttpServletRequest * @return 客户端真实IP */ public static String getIpAddr(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; } /** * 添加指定名字的cookie值 * * @param response * HttpServletResponse * @param cookieName * cookie名 * @param cookieValue * cookie值 * @throws UnsupportedEncodingException */ public static void addCookieByName(HttpServletResponse response, String cookieName, String cookieValue) throws UnsupportedEncodingException { String utf = URLDecoder.decode(cookieValue, "utf-8"); Cookie cookie = new Cookie(cookieName, utf); cookie.setVersion(1); // cookie.setMaxAge(60 * 60 * 24 * 7);// 默认1周内有效 cookie.setMaxAge(60 * 10);// 10分钟有效 cookie.setDomain(ConstUtil.CJTCDOMAINURL); cookie.setPath("/"); response.setHeader("P3P", "CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'"); response.addCookie(cookie); } /** * 删除指定名字的cookie值 * * @param request * HttpServletRequest * @param response * HttpServletResponse * @param cookieName * cookie名 */ public static void deleteCookieByName(HttpServletResponse response, String cookieName) { Cookie cookie = new Cookie(cookieName, ""); cookie.setMaxAge(0); cookie.setDomain(ConstUtil.CJTCDOMAINURL); cookie.setPath("/"); response.setHeader("P3P", "CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'"); response.addCookie(cookie); } /** * 获取指定名字的cookie * * @param request * HttpServletRequest * @param cookieName * cookie名 * @return cookie值 */ public static String getCookieValueByName(HttpServletRequest request, String cookieName) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { // cookie.setDomain(ConstUtil.CJTCDOMAINURL); // cookie.setPath("/"); if (cookie != null && cookieName.equals(cookie.getName())) { logger.debug("cookie.getName():" + cookie.getName() + "\tcookie.getValue():" + cookie.getValue() + "\tcookie.getDomain():" + cookie.getDomain() + "\tcookie.getPath():" + cookie.getPath()); return cookie.getValue(); } } } return null; } }