httpclient 调用接口工具抽取

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;




public class HttpClientMyUtil {
	
	/**
	 * 发送有参数的get的请求
	 * @param url 
	 * @param params 请求参数
	 * @return
	 */
	public static String get(String url,Map params){
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {
			URIBuilder builder = new URIBuilder(url);
			if(params !=null && params.size()>0){
				for(Entry param : params.entrySet()){
					builder.addParameter(param.getKey(), param.getValue());
				}
			}
			HttpGet httpGet = new HttpGet(builder.build());
			
			CloseableHttpResponse response = httpClient.execute(httpGet);
			
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				return EntityUtils.toString(entity, "utf-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 *无参数的get的请求
	 * @param url
	 * @return
	 */
	public static String get(String url){
		
		return get(url,null);
	}
	
	/**
	 * 带参数的post的请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String  post(String url,Map params){
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//构建http post请求
		HttpPost post = new HttpPost(url);
		try {
			UrlEncodedFormEntity from = null;
			if(params != null && params.size()>0){
				List nValuePairs = new ArrayList();
				for(Entry entry : params.entrySet()){
					nValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				from = new UrlEncodedFormEntity(nValuePairs,"utf-8");
				post.setEntity(from);
			}
			//发送请求
			CloseableHttpResponse execute =  httpClient.execute(post);
			//获得响应结果
			HttpEntity entity = execute.getEntity();
			//解析响应结果
			return EntityUtils.toString(entity,"utf-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	/**
	 * 调用此方法及有可能使用的此段代码
	 * String json = "";//httpclient 调用接口返回的json数据
		Gson gson = new Gson();
		//通过Gson将json数据封装到list的集合里(集合里装的是Goods实体类)
		List goods = gson.fromJson(json, new TypeToken>(){}.getType());
	 */
}

你可能感兴趣的:(工具类)