httpclient 4.5.1---http工具类

package com.cycore.dbs.common.util;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.http.Consts;
import org.apache.http.HttpStatus;
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.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;


/**
 * Http客户端工具类
 * @author xiawq
 *
 */
public class HttpUtils {


	/**
	 * POST方式提交参数
	 * @param url-请求URL
	 * @param params-键值映射形式入参
	 * @return
	 */
	public static String postParams(String url, Map<String,String> params){
		CloseableHttpClient client = HCManager.getClient();
		HttpPost httpPost = new HttpPost(url);
		
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		if(params != null){
			for(Map.Entry<String, String> entry : params.entrySet()){
				formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		httpPost.setConfig(HCManager.getRequestConfig());
		httpPost.setEntity(entity);
		try {
			CloseableHttpResponse response = client.execute(httpPost,HttpClientContext.create());
			try {
				if (response.getStatusLine() != null 
						&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					InputStream is = response.getEntity().getContent();;
					try {
						return readInputStream(is, ContentType.get(entity).getCharset());
					} finally {
						is.close();
					}
				} 
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * POST方式提交请求
	 * @param url-请求URL
	 * @param jsonStr-请求参数json格式
	 * @return
	 */
	public static String postJson(String url, String jsonStr){
		CloseableHttpClient client = HCManager.getClient();
		HttpPost httpPost = new HttpPost(url);
		
		StringEntity entity = new StringEntity(jsonStr,ContentType.APPLICATION_JSON);
		httpPost.setConfig(HCManager.getRequestConfig());
		httpPost.setEntity(entity);
		try {
			CloseableHttpResponse response = client.execute(httpPost, HttpClientContext.create());
			try {
				if (response.getStatusLine() != null 
						&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					InputStream is = response.getEntity().getContent();
					try {
						return readInputStream(is, ContentType.get(entity).getCharset());
					} finally {
						is.close();
					}
				} 
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * GET方式提交请求
	 * @param url-请求URL(待测试)
	 * @return
	 */
	public static String getMethod(String url){
		CloseableHttpClient client = HCManager.getClient();
		HttpGet httpGet = new HttpGet(url);
		
		httpGet.setConfig(HCManager.getRequestConfig());
		httpGet.addHeader(new BasicHeader("Content-Type", "multipart/form-data;charset=utf-8"));
		try {
			CloseableHttpResponse response = client.execute(httpGet, HttpClientContext.create());
			try {
				if(response.getStatusLine() != null 
						&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
					InputStream is = response.getEntity().getContent();
					try {
						return readInputStream(is, Consts.UTF_8);
					} finally {
						is.close();
					}
				}
			} finally {
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 读取流
	 * @param is-输入流
	 * @param charset-编码格式
	 * @return
	 */
	public static String readInputStream(InputStream is, Charset charset){
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		String result = "";
		if(is != null){
			try {
				while((len = is.read(buffer)) != -1){
					outputStream.write(buffer, 0, len);
				}
				result = new String(outputStream.toByteArray(), charset);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
//		(1)postJson方法测试
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("uid", "101");
//		params.put("uuidList", new ArrayList<String>(){
//			{
//				add("a1c726b9-a66a-4129-b3dc-2dd8bffd4123");
//			}
//		});
//		String url = "http://localhost:8080/cycore-databus-bundle/question/deleteQuestionByIds";
//		String result=HttpUtils.postJson(url, JsonUtils.obj2Json(params));
//		System.out.println(result);
		
//		(2)postParams方法测试
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("subject", "03");
//		params.put("phase", "03");
//		String url = "http://localhost:8080/cycore-databus-bundle/question/retrieveTSectionList";
//		String result=HttpUtils.postParams(url, params);
//		System.out.println(result);
	}
}

你可能感兴趣的:(httpclient)