Http工具类

http工具类

package com.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

import com.chinainsurance.application.common.BeanManager;
import com.chinainsurance.application.common.https.MySecureProtocolSocketFactory;
import com.chinainsurance.application.platform.dto.domain.GgRiskConfigValueDto;
import com.chinainsurance.application.platform.persistence.dao.GgRiskConfigValueDao;

public class HttpUtils {
	/**
	 * 获取响应报文
	 * @param request
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getResponseXml(String requestXml, String url) throws Exception {
		StringBuilder buffer = new StringBuilder();
		InputStream inputStream = null;
		BufferedReader reader = null;
		String strMessage = "";
		HttpClient httpClient = new HttpClient();
		HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(10000);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(60000);
		PostMethod postMethod = new PostMethod(url);
  	    // 将请求参数XML的值放入postMethod中
		try {
			postMethod.setRequestEntity(new StringRequestEntity(requestXml,"application/xml", "UTF-8"));
			//获取http状态返回代码 200-服务器成功返回网页
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != 200) {
				throw new IllegalStateException("Method failed: " + postMethod.getStatusLine());
			}
			inputStream = postMethod.getResponseBodyAsStream();
			reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((strMessage = reader.readLine()) != null){
				buffer.append(strMessage);
			}
		} catch (Exception ex) {
			throw new IllegalStateException(ex.toString());
		} finally {
			//释放连接
			postMethod.releaseConnection();
		}
		return buffer.toString();
	}
	
	/**
	 * 获取响应报文
	 * @param request
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getResponseJson(String requestJson, String url) throws Exception {
		StringBuilder buffer = new StringBuilder();
		InputStream inputStream = null;
		BufferedReader reader = null;
		String strMessage = "";
		HttpClient httpClient = new HttpClient();
		HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(10000);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(60000);
		PostMethod postMethod = new PostMethod(url);
		// 将请求参数XML的值放入postMethod中
		try {
			postMethod.setRequestEntity(new StringRequestEntity(requestJson,"application/json", "UTF-8"));
			//获取http状态返回代码 200-服务器成功返回网页
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != 200) {
				throw new IllegalStateException("Method failed: " + postMethod.getStatusLine());
			}
			inputStream = postMethod.getResponseBodyAsStream();
			reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((strMessage = reader.readLine()) != null){
				buffer.append(strMessage);
			}
		} catch (Exception ex) {
			throw new IllegalStateException(ex.toString());
		} finally {
			//释放连接
			postMethod.releaseConnection();
		}
		return buffer.toString();
	}
	
	/**
	 * 获取请求报文
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public static String readRequest(HttpServletRequest request, HttpServletResponse response)throws Exception{
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        try{	        
	        is = request.getInputStream();//获取HTTP请求的输入流	
	        //给HTTP请求输入流建立一个BufferedReader对象
	        br = new BufferedReader(new InputStreamReader(is,"UTF-8"));	        
	        String buffer = null;//读取HTTP请求内容
	        //在页面中显示读取到的请求参数	
	        while ((buffer = br.readLine()) != null) {        
	            sb.append(buffer+"\n");
	        }
        }catch(Exception e){
        	throw new RuntimeException("读取请求报文异常");
        }finally{
        	br.close();
        	is.close();
        }
       return sb.toString();
	}
	
	/**
	 * 调用https地址(使用代理并且绕过证书调用)
	 * @param requestXml
	 * @param url
	 * @return
	 */
	public static String httpsXml(String requestXml,String url)throws Exception{

		StringBuilder buffer = new StringBuilder();
		InputStream inputStream = null;
		BufferedReader reader = null;
		String strMessage = "";
		// 声明
		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
		// 加入相关的https请求方式
		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		HttpClient httpClient = new HttpClient();
		//设置代理
		//本地:"10.6.5.12", 40002
		//测试环境:"172.30.30.12", 40000
		/*String proxyHost = "10.6.5.12";
		Integer proxyPort = 0;
		String proxyPortTmp = "40002";
		if(proxyPortTmp != null && proxyPortTmp.trim().length() >0){
			proxyPort = Integer.valueOf(proxyPortTmp);
		}*/
		//设置代理
		GgRiskConfigValueDao ggRiskConfigValueDao = (GgRiskConfigValueDao)BeanManager.getBean("ggRiskConfigValueDao");
		GgRiskConfigValueDto proxyHostDto = ggRiskConfigValueDao.findByPrimaryKey("03", "1039", "SHUIDI_PROXYHOST");		
		GgRiskConfigValueDto proxyPortDto = ggRiskConfigValueDao.findByPrimaryKey("03", "1039", "SHUIDI_PROXYPORT");
		String proxyHost = "";
		Integer proxyPort = 0;
		if(proxyHostDto != null && proxyPortDto != null){
			proxyHost = proxyHostDto.getConfigValue();
			String proxyPortTmp = proxyPortDto.getConfigValue();
			if(proxyPortTmp != null && proxyPortTmp.trim().length() >0){
				proxyPort = Integer.valueOf(proxyPortTmp);
			}
		}
		
	
		httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);//设置代理
		httpClient.getParams().setAuthenticationPreemptive(true);
		
		HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(10000);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(60000);
		PostMethod postMethod = new PostMethod(url);
  	    // 将请求参数XML的值放入postMethod中
		try {
			postMethod.setRequestEntity(new StringRequestEntity(requestXml,"application/xml", "UTF-8"));
			//获取http状态返回代码 200-服务器成功返回网页
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != 200) {
				throw new IllegalStateException("Method failed: " + postMethod.getStatusLine());
			}
			inputStream = postMethod.getResponseBodyAsStream();
			reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((strMessage = reader.readLine()) != null){
				buffer.append(strMessage);
			}
		} catch (Exception ex) {
			throw new IllegalStateException(ex.toString());
		} finally {
			//释放连接
			postMethod.releaseConnection();
		}
		return buffer.toString();
	}
	
	/**
	 * 调用https地址(使用代理并且绕过证书调用)
	 * @param requestJson
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String httpsJson(String requestJson, String url, String proxyInd) throws Exception {
		StringBuilder buffer = new StringBuilder();
		InputStream inputStream = null;
		BufferedReader reader = null;
		String strMessage = "";
		// 声明
		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
		// 加入相关的https请求方式
		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		HttpClient httpClient = new HttpClient();
		//设置代理
		GgRiskConfigValueDao ggRiskConfigValueDao = (GgRiskConfigValueDao)BeanManager.getBean("ggRiskConfigValueDao");
		GgRiskConfigValueDto proxyHostDto = ggRiskConfigValueDao.findByPrimaryKey("03", "1039", "SHUIDI_PROXYHOST");		
		GgRiskConfigValueDto proxyPortDto = ggRiskConfigValueDao.findByPrimaryKey("03", "1039", "SHUIDI_PROXYPORT");
		String proxyHost = "";
		Integer proxyPort = 0;
		if(proxyHostDto != null && proxyPortDto != null){
			proxyHost = proxyHostDto.getConfigValue();
			String proxyPortTmp = proxyPortDto.getConfigValue();
			if(proxyPortTmp != null && proxyPortTmp.trim().length() >0){
				proxyPort = Integer.valueOf(proxyPortTmp);
			}
		}
		if("1".equals(proxyInd)){
			httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);//设置代理
		}
		httpClient.getParams().setAuthenticationPreemptive(true);
		
		HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(10000);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(60000);
		PostMethod postMethod = new PostMethod(url);
  	    // 将请求参数XML的值放入postMethod中
		try {
			postMethod.setRequestEntity(new StringRequestEntity(requestJson,"application/json", "UTF-8"));
			//获取http状态返回代码 200-服务器成功返回网页
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != 200) {
				throw new IllegalStateException("Method failed: " + postMethod.getStatusLine());
			}
			inputStream = postMethod.getResponseBodyAsStream();
			reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((strMessage = reader.readLine()) != null){
				buffer.append(strMessage);
			}
		} catch (Exception ex) {
			throw new IllegalStateException(ex.toString());
		} finally {
			//释放连接
			postMethod.releaseConnection();
		}
		return buffer.toString();
	}
}

补充

package com.chinainsurance.application.common;

/**
 * @author 
 */
public class BeanManager {
    private static final BeanManager instance = new BeanManager();

    private SpringContainer springContainer;

    private BeanManager() {
    }

    public static BeanManager getInstance() {
        return instance;
    }

    public void setSpringContainer(SpringContainer springContainer) {
        this.springContainer = springContainer;
    }

    private SpringContainer getSpringContainer() {
        return springContainer;
    }

    public static Object getBean(String name) {
        return getInstance().getSpringContainer().getComponent(name);
    }
}
package com.chinainsurance.application.common.https;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;

public class MySecureProtocolSocketFactory implements
		SecureProtocolSocketFactory {
	private SSLContext sslContext = null;

	public MySecureProtocolSocketFactory() {
	}
	private static SSLContext createEasySSLContext() {
		try {
			SSLContext context = SSLContext.getInstance("SSL");
			context.init(null, new TrustManager[] { new MyX509TrustManager() },
					null);
			return context;
		} catch (Exception e) {
			throw new HttpClientError(e.toString());
		}
	}
	private SSLContext getSSLContext() {
		if (this.sslContext == null) {
			this.sslContext = createEasySSLContext();
		}
		return this.sslContext;
	}
	public Socket createSocket(String host, int port, InetAddress clientHost,
			int clientPort) throws IOException, UnknownHostException {

		return getSSLContext().getSocketFactory().createSocket(host, port,
				clientHost, clientPort);
	}
	public Socket createSocket(final String host, final int port,
			final InetAddress localAddress, final int localPort,
			final HttpConnectionParams params) throws IOException,
			UnknownHostException, ConnectTimeoutException {
		if (params == null) {
			throw new IllegalArgumentException("Parameters may not be null");
		}
		int timeout = params.getConnectionTimeout();
		if (timeout == 0) {
			return createSocket(host, port, localAddress, localPort);
		} else {
			return ControllerThreadSocketFactory.createSocket(this, host, port,
					localAddress, localPort, timeout);
		}
	}

	public Socket createSocket(String host, int port) throws IOException,
			UnknownHostException {
		return getSSLContext().getSocketFactory().createSocket(host, port);
	}

	public Socket createSocket(Socket socket, String host, int port,
			boolean autoClose) throws IOException, UnknownHostException {
		return getSSLContext().getSocketFactory().createSocket(socket, host,
				port, autoClose);
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值