`

HttpClient应用

阅读更多

Http通讯封装类

其中包含登录,Post请求(不同参数),Get请求(不同参数)等方法

/**
 * HttpCommunicationUtil.java
 * 
 * 功能:Http通讯通用类
 * 类名:HttpCommunicationUtil
 * 
 *   ver     			变更日                    	部门               	开发者     			变更内容
 * ─────────────────────────────────────────────────────
 *   V1.00  		2015-04-20             研发部	         常宝龙          		初版
 *   
 *   Copyright (c) 2008, 2013 Infopower corporation All Rights Reserved.
 */
package com.syxp.yjjkService.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.protocol.RequestAcceptEncoding;
import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * Http通讯通用类
 * 
 * @author 常宝龙
 * 
 */
public class HttpCommunicationUtil {

	/**
	 * 日志输出工具
	 */
	private static Logger logger = Logger
			.getLogger(HttpCommunicationUtil.class);
	/**
	 * Http连接客户端
	 */
	private DefaultHttpClient httpClient = null;
	/**
	 * Socket超时时长,单位毫秒 读取或者接收Socket时长
	 */
	private Integer socketTimeout = 150 * 1000;
	/**
	 * 连接超时时长,单位毫秒 连接HTTP服务器时长。
	 */
	private Integer connectionTimeout = 120 * 1000;

	/**
	 * 构造方法 用于初始化Http客户端
	 */
	public HttpCommunicationUtil() {
		// 获取端口配置信息
		ResourceBundle rb = ResourceBundle.getBundle("config");
		String hostIp = rb.getString("gold.host.ip");
		Integer hostPort = 80;
		try {
			hostPort = Integer.parseInt(rb.getString("gold.host.port"));
		} catch (Exception e) {
			hostPort = 80;
			logger.info("采集主机端口配置错误,使用HTTP默认端口80", e);
		}
		// 协议模拟
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", hostPort, PlainSocketFactory
				.getSocketFactory()));
		// 客户端连接池
		PoolingClientConnectionManager cm = new PoolingClientConnectionManager(
				schemeRegistry);
		// 客户端总并行链接最大数
		cm.setMaxTotal(100);
		// 每个主机的最大并行链接数
		cm.setDefaultMaxPerRoute(50);
		// 为hostIp设置最大连接数
		cm.setMaxPerRoute(new HttpRoute(new HttpHost(hostIp, hostPort)), 50);
		// 设置头信息,模拟浏览器
		httpClient = new DefaultHttpClient(cm);
		httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.BROWSER_COMPATIBILITY);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.WAIT_FOR_CONTINUE, 5000);
		httpClient
				.getParams()
				.setParameter(CoreProtocolPNames.USER_AGENT,
						"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)");
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				socketTimeout);
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
		httpClient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY,
				true);
		// 旧连接检查
		httpClient.getParams().setParameter(
				CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
		httpClient.getParams().setParameter("Accept-Language",
				"zh-cn,zh,en-US,en;q=0.5");
		httpClient.getParams().setParameter("Accept-Charset",
				"utf-8,gbk,gb2312,ISO-8859-1;q=0.7,*;q=0.7");
		httpClient.getParams().setParameter("Accept-Encoding", "gzip, deflate");
		httpClient.getParams().setParameter("Cache-Control", "no-cache");
		httpClient.addRequestInterceptor(new RequestAcceptEncoding());
		httpClient.addResponseInterceptor(new ResponseContentEncoding());
	}

	/**
	 * 登录
	 * 
	 * @param loginUrl
	 *            登录URL地址
	 * @param loginMap
	 *            登录参数
	 * @return true:登录成功;false:登录失败
	 * @throws Exception
	 */
	public boolean login(String loginUrl, Map<String, String> loginMap)
			throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (String key : loginMap.keySet()) {
			params.add(new BasicNameValuePair(key, loginMap.get(key)));
		}
		HttpPost httppost = new HttpPost(loginUrl);
		try {
			// 设置params编码
			UrlEncodedFormEntity uefEntity = null;
			if (params != null && params.size() > 0) {
				uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
				httppost.setEntity(uefEntity);
			}
			HttpResponse response;
			// 获取系统时间,计算运行时间
			long st = System.currentTimeMillis();
			response = httpClient.execute(httppost);
			long et1 = System.currentTimeMillis();
			String resContent = EntityUtils.toString(response.getEntity(),
					"UTF-8");
			long et = System.currentTimeMillis();
			System.out.println("运行时间:" + (et1 - st) + " 耗费时间:" + (et - st));
			logger.debug(resContent);
			logger.debug(loginUrl + " Post请求响应状态:"
					+ response.getStatusLine().getStatusCode());
			if (!(response.getStatusLine().getStatusCode() == 404 || response
					.getStatusLine().getStatusCode() == 500)) {
				return true;
			}
		} finally {
			httppost.releaseConnection();
		}
		return false;
	}

	/**
	 * 访问https网站
	 * 
	 * @param useSSL
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 */
	public HttpCommunicationUtil(boolean useSSL) throws KeyManagementException,
			NoSuchAlgorithmException {
		PoolingClientConnectionManager ccm = null;
		if (useSSL) {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				@Override
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ccm = new PoolingClientConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));
		} else {
			SchemeRegistry schemeRegistry = new SchemeRegistry();
			schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
					.getSocketFactory()));
			ccm = new PoolingClientConnectionManager(schemeRegistry);
		}
		// 生成httpClient
		httpClient = new DefaultHttpClient(ccm);
		httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.BROWSER_COMPATIBILITY);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.WAIT_FOR_CONTINUE, 5000);
		httpClient
				.getParams()
				.setParameter(CoreProtocolPNames.USER_AGENT,
						"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)");
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				120000);
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 120000);
		httpClient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY,
				true);
		httpClient.getParams().setParameter(
				CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
		httpClient.getParams().setParameter("Accept-Language",
				"zh-cn,zh,en-US,en;q=0.5");
		httpClient.getParams().setParameter("Accept-Charset",
				"utf-8,gbk,gb2312,ISO-8859-1;q=0.7,*;q=0.7");
		httpClient.getParams().setParameter("Accept-Encoding", "gzip, deflate");
		httpClient.getParams().setParameter("Cache-Control", "no-cache");
		httpClient.addRequestInterceptor(new RequestAcceptEncoding());
		httpClient.addResponseInterceptor(new ResponseContentEncoding());
	}

	/**
	 * 发送HTTP Post请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param params
	 *            请求参数
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws ResponseException
	 */
	public String doPost(String url, List<NameValuePair> params)
			throws Exception {
		HttpPost httppost = new HttpPost(url);
		try {
			UrlEncodedFormEntity uefEntity = null;
			if (params != null && params.size() > 0) {
				uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
				httppost.setEntity(uefEntity);
			}
			HttpResponse response;
			response = httpClient.execute(httppost);
			logger.debug(url + " Post请求响应状态:" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resContent = EntityUtils.toString(entity, "UTF-8");
				return resContent;
			}
		} catch (Exception e) {
			logger.error("HttpPost请求异常", e);
			httppost.abort();
		} finally {
			httppost.releaseConnection();
		}
		return null;
	}

	/**
	 * 发送HTTP Post请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws ResponseException
	 */
	public String doPost(String url) throws Exception {
		HttpPost httppost = new HttpPost(url);
		try {
			HttpResponse response;
			response = httpClient.execute(httppost);
			logger.debug(url + " Get请求响应状态:" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resContent = EntityUtils.toString(entity, "UTF-8");
				return resContent;
			}
		} catch (Exception e) {
			logger.error("HttpPost请求异常", e);
			httppost.abort();
		} finally {
			httppost.releaseConnection();
		}
		return null;
	}

	/**
	 * 发送HTTP Post请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param bytes
	 *            请求参数
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws ResponseException
	 */
	public String doPost(String url, byte[] bytes) throws Exception {
		String resultXML = null;
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Content-Type", "application/x-amf");
		ByteArrayEntity be = new ByteArrayEntity(bytes);
		httppost.setEntity(be);
		HttpResponse response;
		try {
			response = httpClient.execute(httppost);
			logger.info(" Post请求响应状态:" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			byte[] arr = new byte[512];
			InputStream is = entity.getContent();
			StringBuffer sb = new StringBuffer();
			do {
				int n = is.read(arr);
				if (n == -1)
					break;
				ByteBuffer buf = ByteBuffer.allocate(n);
				buf.put(arr, 0, n);
				sb.append(new String(buf.array()));
			} while (true);
			resultXML = sb.toString();
		} catch (ClientProtocolException e) {
			logger.error("HttpPost请求异常", e);
		} catch (IOException e) {
			logger.error("HttpPost请求异常", e);
		}
		return resultXML;
	}

	/**
	 * 发送HTTP Post请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param requestContent
	 *            请求参数
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws ResponseException
	 */
	public String doPost(String url, String requestContent) throws Exception {
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
		StringEntity se = new StringEntity(requestContent, ContentType.create(
				"text/xml", "UTF-8"));
		httppost.setEntity(se);
		HttpResponse response;
		try {
			response = httpClient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resContent = EntityUtils.toString(entity, "UTF-8");
				return resContent;
			}
		} catch (ClientProtocolException e) {
			logger.error("HttpPost请求异常", e);
		} catch (IOException e) {
			logger.error("HttpPost请求异常", e);
		}
		return null;
	}

	/**
	 * 发送HTTP Get请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param charset
	 *            请求参数
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws ResponseException
	 */
	public String doGet(String url, String charset) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response;
			response = httpClient.execute(httpGet);
			logger.debug(url + " Get请求响应状态:" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resContent = EntityUtils.toString(entity, charset);
				return resContent;
			}
		} catch (Exception e) {
			logger.error("HttpGet请求异常", e);
			httpGet.abort();
		} finally {
			httpGet.releaseConnection();
		}
		return null;
	}

	/**
	 * 发送HTTP Get请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws ResponseException
	 */
	public String doGet(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response;
			response = httpClient.execute(httpGet);
			logger.debug(url + " Get请求响应状态:" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resContent = EntityUtils.toString(entity, "UTF-8");
				return resContent;
			}
		} catch (Exception e) {
			logger.error("HttpGet请求异常", e);
			httpGet.abort();
		} finally {
			httpGet.releaseConnection();
		}
		return null;
	}

	/**
	 * 发送HTTP Get请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @return
	 */
	public String doGetJson(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		try {
			httpGet.addHeader("accept", "application/json");
			httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
			HttpResponse response;
			response = httpClient.execute(httpGet);
			logger.debug(url + " Get请求响应状态:" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resContent = EntityUtils.toString(entity, "UTF-8");
				return resContent;
			}
		} catch (Exception e) {
			logger.error("HttpGet请求异常", e);
			httpGet.abort();
		} finally {
			httpGet.releaseConnection();
		}
		return null;
	}

	/**
	 * 发送HTTP Get请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param context
	 *            请求上下文
	 * @return
	 */
	public String doGet(String url, HttpContext context) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response;
			if (context != null) {
				response = httpClient.execute(httpGet, context);
			} else {
				response = httpClient.execute(httpGet);
			}
			logger.debug(url + " Get请求响应状态:" + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resContent = EntityUtils.toString(entity, "UTF-8");
				return resContent;
			}
		} catch (Exception e) {
			logger.error("HttpGet请求异常", e);
			httpGet.abort();
		} finally {
			httpGet.releaseConnection();
		}
		return null;
	}

	/**
	 * 取得连接客户端Cookie
	 * 
	 * @return
	 */
	public List<Cookie> getCookies() {
		return httpClient.getCookieStore().getCookies();
	}

	/**
	 * 设置连接客户端Cookie
	 * 
	 * @param cookies
	 */
	public void setCookie(List<Cookie> cookies) {
		for (Cookie cookie : cookies) {
			httpClient.getCookieStore().addCookie(cookie);
		}
	}

	/**
	 * 根据Cookie名称取得Cookie值
	 * 
	 * @param cookieName
	 *            Cookie名称
	 * @return
	 */
	public String getCookieValue(String cookieName) {
		List<Cookie> cookies = httpClient.getCookieStore().getCookies();
		if (cookies != null && cookies.size() > 0) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(cookieName)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * 关闭httpClient连接
	 */
	public void close() {
		if (httpClient != null) {
			httpClient.getConnectionManager().shutdown();
			logger.debug("关闭HTTP连接。");
		}
	}

	/**
	 * 
	 * @param args
	 * @throws Exception
	 * @since Ver 1.0
	 */
	public static void main(String[] args) throws Exception {
		HttpCommunication hc = null;
		try {
			hc = new HttpCommunication(true);
			// 登录测试
			String loginUrl = "http://localhost:8080/yjjk/login/login_login";
			Map<String, String> loginMap = new HashMap<String, String>();
			loginMap.put("user.userName", "admin");
			loginMap.put("user.userPwd", "admin");
			boolean temp = hc.login(loginUrl, loginMap);
			System.out.println(temp);
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
}

 

2
1
分享到:
评论
2 楼 cnrainbing 2015-04-21  
兄弟写的非常漂亮支持!
1 楼 endual 2015-04-21  
模拟登陆失败,可否帮看下?

相关推荐

    HttpClient应用实例2

    标题中的"HttpClient应用实例2"指的是使用Apache HttpClient库进行HTTP通信的一个具体示例或教程。HttpClient是一个成熟的Java库,用于执行HTTP请求并处理响应。它提供了丰富的功能,包括支持HTTPS、连接管理、重试...

    apache-httpclient应用所有jar

    1. **异步和同步API**: HttpClient 提供了同步和异步两种API,以适应不同的应用场景。同步API适合于简单且线性的工作流,而异步API则适用于处理大量并发请求,提高了系统性能。 2. **全面的HTTP协议支持**: ...

    httpclient应用

    HttpClient是Apache基金会开发的一个Java库,它为Java程序员提供了一个强大的、灵活的、功能丰富的HTTP客户端API,使得处理HTTP...通过深入学习和熟练掌握HttpClient的使用,你将能够更高效地开发和维护Java网络应用。

    C#HTTPclient 实例应用

    在本文中,我们将深入探讨`HttpClient`的实例应用,以及如何使用它来实现各种HTTP操作。 ### 1. `HttpClient`的基本用法 创建`HttpClient`实例通常是通过静态`HttpClientFactory`方法或直接实例化`HttpClient`完成...

    httpclient开发所必须架包

    在描述中提到的是"开发所必须架包",这通常意味着该压缩包包含了运行和开发HTTPClient应用程序所需的所有依赖项。这些依赖可能包括但不限于以下几点: 1. **HTTPCore**: HTTPClient的基础组件,提供低级别的HTTP...

    HTTPClient组件的应用

    HttpClient组件允许应用程序直接通过HTTP协议访问Web服务器上的资源,这对于RIA(Rich Internet Applications)和Web服务客户端的开发尤其有用。 HttpClient组件的主要特点和功能包括: 1. 实现了HTTP 1.0和1.1的...

    基于java httpclient的12306 买票软件, 仅供学习使用.zip

    对于12306购票的实现,可以研究其API接口文档,以及已有的开源项目,如"基于java httpclient的12306 买票软件",从中学习如何将HttpClient应用于实际场景。 通过以上内容,我们可以了解到Java HttpClient在实现...

    httpClient

    java httpClient应用,包含了设置代理等功能。

    如何在WPF应用程序中通过HttpClient调用Web API

    在WPF(Windows Presentation Foundation)应用程序中,使用HttpClient调用Web API是一项常见的任务,尤其是在进行数据交互时。本文将深入探讨如何在WPF应用中利用HttpClient进行异步操作,以避免阻塞主线程,提高...

    HttpClient之Https应用实例

    HttpClient之Https应用实例~ 包含: HttpClient 使用代理访问Https HttpClient 信任所有主机-对于任何证书都不做检查 HttpClient 允许所有证书的校验(包括过期证书)

    httpclient.jar包下载

    《深入解析httpclient.jar及其与code.jar的关联》 在Java开发中,HTTP通信是不可或缺的一部分,而Apache HttpClient库正是Java...理解和熟练掌握HttpClient库,将有助于提升Java应用在网络通信方面的效率和稳定性。

    httpclient httpclient.jar

    在本文中,我们将深入探讨HttpClient的核心概念、使用方法以及如何通过`httpclient.jar`进行实战应用。 首先,HttpClient的主要组件包括: 1. **HttpClient实例**:这是整个HTTP通信的核心,负责管理连接、请求和...

    httpclient-4.5.3官方API中文文档_最新译版_2886K

    本文将基于4.5.3版本的HttpClient官方API中文文档,深入探讨其核心概念、使用方法及常见应用场景。 一、HttpClient简介 HttpClient是一款高效的HTTP客户端库,它支持多种HTTP标准,包括HTTP/1.1、HTTP/2以及...

Global site tag (gtag.js) - Google Analytics