天天看點

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];
	}
}