HttpClient工具类,完成Get和Post请求

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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;

/**
 * HttpClient工具类,完成Get和Post请求
 * @Description:
 * @ClassName:     HttpClientUtils
 *
 */
public class HttpClientUtils {
	
	/**
	 * Get请求,有参
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doGet(String url,Map<String,String> params){
		//1.创建HttpClient
		CloseableHttpClient client = HttpClients.createDefault();
		URIBuilder uriBuilder = null;
		URI uri = null;
		HttpGet get = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String resData = "";
		try {
			//     进行参数封装
			uriBuilder = new URIBuilder(url);
			if(params!=null){
				for(Map.Entry<String, String> entry : params.entrySet()) {
					uriBuilder.addParameter(entry.getKey(), entry.getValue());
				}
			}
			uri = uriBuilder.build();
			//2.创建HttpGet
			get = new HttpGet(uri);
			//3.执行get请求
			response = client.execute(get);
			if(response.getStatusLine().getStatusCode()==200) {
				//4.获取相应结果,封装进HttpEntity中
				entity = response.getEntity();
				//HttpEntity转字符串
				resData = EntityUtils.toString(entity,"UTF-8");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(response!=null) 
					response.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resData;
	}
	
	/**
	 * Get请求,无参
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		return doGet(url, null);
	}
	
	/**
	 * Post请求,数据格式是<key,value>参数
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPostForm(String url,Map<String,String> params) {
		//1.创建HttpClient
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resData = "";
		try {
			//2.创建HttpPost
			HttpPost post = new HttpPost();
			// 参数封装
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			for(Map.Entry<String, String> entry : params.entrySet()) {
				NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
				list.add(nameValuePair);
			}
			UrlEncodedFormEntity UrlEntity = new UrlEncodedFormEntity(list,"UTF-8");
			post.setEntity(UrlEntity);
			//3.执行post请求
			response = client.execute(post);
			//4.接收相应数据
			HttpEntity entity = response.getEntity();
			//转字符串
			resData = EntityUtils.toString(entity,"UTF-8");
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(response!=null) 
					response.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resData;
	}
	
	/**
	 * Post请求,数据格式是json
	 * @param url
	 * @param json
	 * @return
	 */
	public static String doPostJson(String url,String json) {
		//1.创建HttpClient
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resData = "";
		try {
			//2.创建HttpPost
			HttpPost post = new HttpPost();
			// 参数封装
			StringEntity strEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
			post.setEntity(strEntity);
			//3.执行post请求
			response = client.execute(post);
			//4.接收相应数据
			HttpEntity entity = response.getEntity();
			//转字符串
			resData = EntityUtils.toString(entity,"UTF-8");
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(response!=null) 
					response.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resData;
	}
	
	/**
	 * 将URL中的参数拼接转化为Map
	 * @param url : 请求的URL完整路径
	 * @return
	 */
	public static Map<String, String> convertMap(String url){
		Map<String, String> map = new HashMap<String, String>();
		
		if(url.contains("?")){
			String paramsStr = url.split("\\?")[1];
			String[] paramKeyValueStrs = paramsStr.split("&");
			for(String paramKeyValue : paramKeyValueStrs){
				String[] mapStr = paramKeyValue.split("=");
				String key = "";
				String value = "";
				if(mapStr.length>1){
					key = mapStr[0]==null ? "" : mapStr[0];
					value = mapStr[1] == null ? "" : mapStr[1];
					map.put(key, value);
				}else if(mapStr.length==1 && paramKeyValue.indexOf("=")>paramKeyValue.indexOf(mapStr[0])){
					key = mapStr[0] == null ? "" : mapStr[0];
					map.put(key, "");
				}
			}
		}
		
		return map;
	}
	
	/**
	 * 获取URL路径中不带参数的请求路径
	 * @param url : 请求的URL完整路径
	 * @return
	 */
	public static String findPathInURL(String url){
		return url.split("\\?")[0] == null ? url : url.split("\\?")[0];
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值