httpClient工具类

张军 4413 0

所有工具类

在日常开发中,我们经常需要通过http协议去调用网络内容,虽然java自身提供了net相关工具包,但是其灵活性和功能总是不如人意,于是有人专门搞出一个httpclient类库,来方便进行Http操作。对于httpcore的源码研究,我们可能并没有达到这种层次,在日常开发中也只是需要的时候,在网上百度一下,然后进行调用就行。在项目中对于这个工具类库也许没有进行很好的封装。在哪里使用就写在哪些,很多地方用到,就在多个地方写。反正是复制粘贴,很方便,但是这样就会导致项目中代码冗余。所以这里简单的对httpcient的简单操作封装成一个工具类,统一放在项目的工具包中,在使用的时候直接从工具包中调用,不需要写冗余代码。

HttpClientUtil

package zj.http.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;

import zj.common.exception.ServiceException;
import zj.http.bean.ICallBackMethod;

/**
 * httpClient工具类
 * 
 * @version 1.00 (2014.09.15)
 * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>}
 */
public class HttpClientUtil {
	private static transient final Logger logger = Logger.getLogger(HttpClientUtil.class);

	/**
	 * get请求
	 * 
	 * @param url
	 *            请求地址
	 * @return 响应数据
	 * @throws Exception
	 */
	public static String get(String url) {
		return get(url, null);
	}

	/**
	 * get请求
	 * 
	 * @param url
	 *            请求地址
	 * @param callBack
	 *            设置参数s
	 * @return 响应数据
	 * @throws Exception
	 */
	public static String get(String url, ICallBackMethod callBack) {
		String resultString = null;
		HttpClient httpClient = new HttpClient();
		GetMethod method = new GetMethod(url);
		try {
			// method.setRequestHeader(new Header("", ""));
			if (callBack != null) {
				callBack.setMethod(method);
			}
			int resultCode = httpClient.executeMethod(method);
			if (resultCode == 200) {
				resultString = method.getResponseBodyAsString();
			}
			logger.debug("调用方法返回结果[" + resultCode + "]:" + resultString);
			return resultString;
		} catch (Exception e) {
			throw new ServiceException(e);
		} finally {
			if (method != null) {
				try {
					method.releaseConnection();
				} catch (Exception e2) {
				}
			}
			if (httpClient != null) {
				// 上面的httpPost.releaseConnection()只是把连接归还client,没有关闭
				// 加上下面这一句,才真正把不用的连接关闭
				// 如果不手动关闭连接,每个连接都是保持180秒后才会自动断开,会占用大量的连接。
				try {
					httpClient.getHttpConnectionManager().closeIdleConnections(0);
				} catch (Exception e) {
					logger.info(e.getMessage(), e);
				}
			}
			// try {
			// method.releaseConnection();
			// ((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
		}
	}

	/**
	 * XML.post请求
	 * 
	 * @param url
	 *            请求地址
	 * @param content
	 *            请求内容
	 * @return 响应数据
	 * @throws Exception
	 */
	public static String postXML(String url, String content) {
		return post(url, content, "application/xml", "UTF-8");
	}

	/**
	 * JSON.post请求
	 * 
	 * @param url
	 *            请求地址
	 * @param content
	 *            请求内容
	 * @return 响应数据
	 * @throws Exception
	 */
	public static String postJSON(String url, String content) {
		return post(url, content, "application/json", "UTF-8");
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            请求地址
	 * @param content
	 *            请求内容
	 * @param contentType
	 *            请求类型
	 * @see contentType值说明
	 * @see application/x-www-form-urlencoded:窗体数据被编码为名称/值对。这是标准的编码格式。这是默认的方式
	 * @see multipart/form-data:窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分。二进制数据传输方式,主要用于上传文件
	 * @see text/html
	 * @see text/xml
	 * @param charset
	 *            请求编码
	 * @return 响应数据
	 * @throws Exception
	 */
	public static String post(String url, String content, String contentType, String charset) {
		return post(url, content, contentType, charset, null);
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            请求地址
	 * @param content
	 *            请求内容
	 * @see application/x-www-form-urlencoded:窗体数据被编码为名称/值对。这是标准的编码格式。这是默认的方式
	 * @see multipart/form-data:窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分。二进制数据传输方式,主要用于上传文件
	 * @see text/html
	 * @see text/xml
	 * @param callBack
	 *            设置参数
	 * @return 响应数据
	 * @throws Exception
	 */
	public static String postJSON(String url, String content, ICallBackMethod callBack) {
		return post(url, content, "application/json", "UTF-8", callBack);
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            请求地址
	 * @param content
	 *            请求内容
	 * @param contentType
	 *            请求类型
	 * @see contentType值说明
	 * @see application/x-www-form-urlencoded:窗体数据被编码为名称/值对。这是标准的编码格式。这是默认的方式
	 * @see multipart/form-data:窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分。二进制数据传输方式,主要用于上传文件
	 * @see text/html
	 * @see text/xml
	 * @param charset
	 *            请求编码
	 * @param callBack
	 *            设置参数
	 * @return 响应数据
	 * @throws Exception
	 */
	public static String post(String url, String content, String contentType, String charset, ICallBackMethod callBack) {
		String resultString = null;
		HttpClient httpClient = new HttpClient();
		PostMethod method = new PostMethod(url);
		try {
			if (callBack == null) {
				// 默认设置请求类型
				method.setRequestHeader(new Header("Content-Type", contentType));
			} else {
				callBack.setMethod(method);
			}
			// method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "");
			// 禁用重试
			// DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);
			// method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);// 重试次数0次
			// httpClient.setParams(new HttpClientParams() {
			// private static final long serialVersionUID = 1458469810048748607L;
			// {
			// // setSoTimeout(uploadTimeOut);
			// // 连接超时时间
			// setSoTimeout(120000);
			// }
			// });
			// contentType值说明
			// application/x-www-form-urlencoded:窗体数据被编码为名称/值对。这是标准的编码格式。这是默认的方式
			// multipart/form-data:窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分。二进制数据传输方式,主要用于上传文件
			// text/plain:窗体数据以纯文本形式进行编码,其中不含任何控件或格式字符。
			method.setRequestEntity(new StringRequestEntity(content, contentType, charset));
			int resultCode = httpClient.executeMethod(method);
			if (resultCode == 200) {
				resultString = method.getResponseBodyAsString();
			}
			logger.debug("调用方法返回结果[" + resultCode + "]:" + resultString);
			return resultString;
		} catch (Exception e) {
			throw new ServiceException(e);
		} finally {
			if (method != null) {
				try {
					method.releaseConnection();
				} catch (Exception e2) {
				}
			}
			if (httpClient != null) {
				// 上面的httpPost.releaseConnection()只是把连接归还client,没有关闭
				// 加上下面这一句,才真正把不用的连接关闭
				// 如果不手动关闭连接,每个连接都是保持180秒后才会自动断开,会占用大量的连接。
				try {
					httpClient.getHttpConnectionManager().closeIdleConnections(0);
				} catch (Exception e) {
					logger.info(e.getMessage(), e);
				}
			}
			// try {
			// ((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
		}
	}
}

ICallBackMethod

package zj.http.bean;

import org.apache.commons.httpclient.HttpMethodBase;

/**
 * httpClient工具类回调
 * 
 * @version 1.00 (2014.09.15)
 * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>}
 */
public interface ICallBackMethod {
	/**
	 * 设置方法参数
	 * 
	 * @param method
	 */
	public void setMethod(HttpMethodBase method);
}

CallBackMethod

package zj.http.bean;

import org.apache.commons.httpclient.HttpMethodBase;

/**
 * httpClient工具类回调
 * 
 * @version 1.00 (2014.09.15)
 * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>}
 */
public class CallBackMethod implements ICallBackMethod{
	@Override
	public void setMethod(HttpMethodBase method) {
	}
}

测试类

        @Test
	public void get测试() throws Exception {
		try {
			String newUrl = "http://www.baidu.com";
			String r = HttpClientUtil.get(newUrl);
			System.out.println(r);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Test
	public void post测试() throws Exception {
		try {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			jsonMap.put("name", "8779001");
			jsonMap.put("password", "123");
			String json = JSON.toJSONString(jsonMap);
			String r = HttpClientUtil.postJSON("https://agent.ybagent9.com/login", json);
			System.out.println(r);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论