Java Http 发送请求_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java Http 发送请求

Java Http 发送请求

 2015/4/20 21:13:19  为了明天而努力  程序员俱乐部  我要评论(0)
  • 摘要:Http通讯封装类其中包含登录,Post请求(不同参数),Get请求(不同参数)等方法/***HttpCommunicationUtil.java**功能:Http通讯通用类*类名:HttpCommunicationUtil**ver变更日部门开发者变更内容*─────────────────────────────────────────────────────*V1.002015-04-20研发部常宝龙初版**Copyright(c)2008
  • 标签:Java HTTP

Http通讯封装类

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

class="java">/**
 * 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();
		}
	}
}

?

发表评论
用户名: 匿名