分享一个简单的HttpClient的例子

在平时的工作中,经常会使用Http去访问其他系统,此时一个Http的工具类就显得非常重要了。给大家分享一个简单的HttpClient的工具类,以备不时之需。

主要包括POST请求、GET请求和如何发送XML数据。

依赖的jar包如下:

 

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.3.6</version>
</dependency>
<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpcore</artifactId>
     <version>4.3.3</version>
</dependency>
<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>fluent-hc</artifactId>
</dependency>
<dependency>
     <groupId>dom4j</groupId>
     <artifactId>dom4j</artifactId>
     <version>1.6.1</version>
</dependency>

 

 

 

 

 

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class HttpClientManager {
	private static int connectionTimeout = 1000;// 连接超时时间,毫秒
	private static int soTimeout = 30000;// 读取数据超时时间,毫秒
	/** HttpClient对象 */
	private static CloseableHttpClient httpclient = HttpClients.
				custom().disableAutomaticRetries().build();
	/*** 超时设置 ****/
	private static RequestConfig requestConfig = RequestConfig.custom()
													.setSocketTimeout(soTimeout)
													.setConnectTimeout(connectionTimeout)
													.build();//设置请求和传输超时时间
	/**
	 * 根据给定的URL地址和参数字符串,以Get方法调用,如果成功返回true,如果失败返回false
	 * 
	 * @param url
	 *            String url地址,不含参数
	 * @param param
	 *            String 参数字符串,例如:a=1&b=2&c=3
	 */
	public String executeGetMethod(String url, String param) {
		String strResult = "";
		StringBuffer serverURL = new StringBuffer(url);
		if (param != null && param.length() > 0) {
			serverURL.append("?");
			serverURL.append(param);
		}
		HttpGet httpget = new HttpGet(serverURL.toString());
		httpget.setConfig(requestConfig);
		CloseableHttpResponse response=null;
		try {
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			int iGetResultCode = response.getStatusLine().getStatusCode();
			if (iGetResultCode >= 200 && iGetResultCode < 303) {
				strResult = EntityUtils.toString(entity);
			} else if (iGetResultCode >= 400 && iGetResultCode < 500) {
				strResult = "请求的目标地址不存在:" + iGetResultCode;
			} else {
				strResult = "请求错误:" + iGetResultCode;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			 try {
				if(response !=null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return strResult;
	}
	
	/**
	 * 根据给定的URL地址和参数字符串,以Get方法调用,如果成功返回true,如果失败返回false
	 * 
	 * @param url
	 *            String url地址,不含参数
	 * @param param
	 *            Map<String, Object> 参数字表单
	 * @return boolean true-成功,false失败,如果返回成功可以getStrGetResponseBody()
	 *         获取返回内容字符串,如果失败,则可访问getErrorInfo()获取错误提示。
	 */
	public String executePostMethod(String strURL, Map<String, String> param) {
		String strResult = "";
		HttpPost post = new HttpPost(strURL);
		post.setConfig(requestConfig);
		List<BasicNameValuePair> paraList = new ArrayList<BasicNameValuePair>(param.size());
		for (Entry<String, String> pEntry : param.entrySet()) {
			if(null != pEntry.getValue()){
				BasicNameValuePair nv = new BasicNameValuePair(pEntry.getKey(), pEntry.getValue());
				paraList.add(nv);
			}
		}
		//使用UTF-8
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paraList,Charset.forName("utf-8"));
		post.setEntity(entity);
		CloseableHttpResponse response=null;
		try {
			response = httpclient.execute(post);
			int iGetResultCode = response.getStatusLine().getStatusCode(); 
			if (HttpStatus.SC_OK == iGetResultCode) {
				HttpEntity responseEntity = response.getEntity();
				strResult = EntityUtils.toString(responseEntity);
			}
			
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if(response!=null){
					response.close();
				}
			} catch (IOException e) {
			}
		}
		return strResult;
	}
	
	/**
	 * 发送xml数据
	 * @param strURL
	 * @param params
	 * @return
	 */
	public String postByXml(String strURL,Map<String,String> params) {
		String strResult = "";
		CloseableHttpResponse response = null;
		try {
			HttpPost post = new HttpPost(strURL);
			post.setConfig(requestConfig);
			post.setHeader("Content-Type", "text/xml;charset=utf-8");
			String xmlData = convertMap2Xml(params);
			StringEntity se = new StringEntity(xmlData);
			post.setEntity(se);
			response = httpclient.execute(post);
			response = httpclient.execute(post);
			int iGetResultCode = response.getStatusLine().getStatusCode(); 
			if (HttpStatus.SC_OK == iGetResultCode) {
				HttpEntity responseEntity = response.getEntity();
				strResult = EntityUtils.toString(responseEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			 try {
				if(response !=null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return strResult;
	}
	/**
	 * 将map转换为xml
	 * @param map
	 */
	private static String convertMap2Xml(Map<String,String> map) {
		Set<Entry<String,String>> entrys = map.entrySet();
		Iterator<Entry<String,String>> iter = entrys.iterator();
		Document doc = DocumentHelper.createDocument();
		Element root = DocumentHelper.createElement("xml");
		while(iter.hasNext()) {
			Entry<String,String> entry = iter.next();
			Element key = DocumentHelper.createElement(entry.getKey());
			key.addCDATA(entry.getValue());
			root.add(key);
		}
		doc.add(root);
		return doc.asXML();
	}
}



 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(java,httpclient)