HttpClient 发送HTTP请求的工具类

HttpClientUtils 发送HTTP请求的方法

/**
 * 封装了一些采用 HttpClient发送HTTP请求的方法
 */
public class HttpClientUtils {	
	
	 /** 连接超时时间 */
    private static int CONNECT_TIME_OUT = 15 * 1000;

    /** 读取超时时间 */
    private static int READ_TIME_OUT = 30 * 1000;//40秒

	private HttpClientUtils() {
	}

	
	public static String get(String reqURL) {
		log.info("get() 请求  reqURL: {} ", reqURL);
		CloseableHttpClient httpClient = null;
		HttpGet httpGet = null;
		String responseResult = null; // 响应内容
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			httpGet = new HttpGet(reqURL);
			httpGet.setConfig(doRequestConfig());
			response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity(); // 获取响应实体
			if (null != entity) {
				responseResult = EntityUtils.toString(entity, "UTF-8");
				EntityUtils.consume(entity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.error("该异常通常是协议错误. {}", e);
		} catch (ParseException e) {
			e.printStackTrace();
			log.error("解析异常. {}", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("该异常通常是网络原因引起的.  {}", e);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("异常信息:", e);
		} finally {
			closeHttp(response, httpClient);
		}
		return responseResult;
	}

	/**
	 * 发送post 请求(json格式)
	 * 
	 * @param reqURL
	 * @param jsonDataStr
	 * @return result
	 */
	public static String postJson(String reqURL, String jsonDataStr) {
		log.info("postJson()请求  reqURL: {} ,jsonDataStr: {}", reqURL, jsonDataStr);
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		String responseResult = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			httpPost = new HttpPost(reqURL);
			httpPost.setConfig(doRequestConfig());
			httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");

			StringEntity entity = new StringEntity(jsonDataStr, "UTF-8");
			entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
			entity.setContentType("application/json");

			httpPost.setEntity(entity);
			response = httpClient.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();
			if (httpEntity != null) {
				responseResult = EntityUtils.toString(httpEntity, "UTF-8");
				EntityUtils.consume(httpEntity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.error("该异常通常是协议错误. {}", e);
		} catch (ParseException e) {
			e.printStackTrace();
			log.error("解析异常. {}", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("该异常通常是网络原因引起的.  {}", e);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("异常信息:", e);
		} finally {
			closeHttp(response, httpClient);
		}
		return responseResult;
	}

	/**
	 * 发送post 请求  (x-www-form-urlencoded) 
	 */
	public static String postForm(String reqURL, Map<String, String> param) {
		log.info("postForm()请求   reqURL: {} ,param: {}", reqURL, FastJsonTools.toJSONString(param));
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		String responseResult = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			httpPost = new HttpPost(reqURL);
			httpPost.setConfig(doRequestConfig());
			httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");

			List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数队列
			if (param != null && param.size() > 0) {
				for (Map.Entry<String, String> entry : param.entrySet()) {
					formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}

			httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				responseResult = EntityUtils.toString(entity, "UTF-8");
				EntityUtils.consume(entity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.error("该异常通常是协议错误. {}", e);
		} catch (ParseException e) {
			e.printStackTrace();
			log.error("解析异常. {}", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("该异常通常是网络原因引起的.  {}", e);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("异常信息:", e);
		} finally {
			closeHttp(response, httpClient);
		}
		return responseResult;
	}

	private static void closeHttp(CloseableHttpResponse response, CloseableHttpClient httpClient) {
		try {
			if (response != null) {
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			if (httpClient != null) {
				httpClient.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}	
	
	private static RequestConfig doRequestConfig() {
		RequestConfig requestConfig = RequestConfig.custom()//
				.setConnectTimeout(CONNECT_TIME_OUT)// 连接一个url的连接等待时间
				.setConnectionRequestTimeout(CONNECT_TIME_OUT)//
				.setSocketTimeout(READ_TIME_OUT)// 读取数据超时
				.build();//
		return requestConfig;
	}

}

HttpClientVOUtils 基于HttpClientUtils ,将请求结果 转成 对象

/**
 * HttpClient HTTP 请求结果转换成对象
 */
public class HttpClientVOUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpClientVOUtils.class);

	private static boolean isShowLog = false;

	private HttpClientVOUtils() {
	}

	public static String get(String url) {
		logger.info("get() url : {}", url);
		String html = null;
		try {
			html = HttpClientUtils.get(url);
			if (isShowLog) {
				logger.info("html : {}", html);
			}
		} catch (Exception e) {
			logger.error("get 异常  {}", e);
		}
		return html;
	}

	public static <T> T getVO(String url, Class<T> cls) {
		logger.info("getVO() url : {}", url);
		T vo = null;
		try {
			String html = HttpClientUtils.get(url);
			if (isShowLog) {
				logger.info("html : {}", html);
			}
			if (StringUtils.isNotBlank(html)) {
				vo = FastJsonTools.getJson(html, cls);
			}
		} catch (Exception e) {
			logger.error("getVO 异常  {}", e);
		}
		return vo;
	}

	public static <T> T postFormVO(String url, Map<String, String> data, Class<T> cls) {
		logger.info("postFormVO() url : {} ,param : {}", url, data);
		T vo = null;
		try {
			String html = HttpClientUtils.postForm(url, data);
			if (isShowLog) {
				logger.info("html : {}", html);
			}
			if (StringUtils.isNotBlank(html)) {
				vo = FastJsonTools.getJson(html, cls);
			}
		} catch (Exception e) {
			logger.error("postVO 异常  {}", e);

		}
		return vo;
	}

	public static <T> T postJsonVO(String url, String data, Class<T> cls) {
		logger.info("postJsonVO() url : {} , bodydata: {}", url, data);
		T vo = null;
		try {
			String html = HttpClientUtils.postJson(url, StringUtils.trimToEmpty(data));
			if (isShowLog) {
				logger.info("html : {}", html);
			}
			if (StringUtils.isNotBlank(html)) {
				vo = FastJsonTools.getJson(html, cls);
			}
		} catch (Exception e) {
			logger.error("postJsonVO  异常 {}", e);
		}
		return vo;
	}

}

FastJsonTools 对象转换工具类

public class FastJsonTools {

	private static final SerializeConfig config;
	static {
		config = new SerializeConfig();
		config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
		config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
	}

	private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 输出空置字段
			SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
			SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
			SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
			SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null
	};

	/**
	 * Object 转换成字符串
	 * @param object
	 * @return
	 */
	public static String toJSONFeaturesString(Object object) {
		return JSON.toJSONString(object, config, features);
	}

	/**
	 * Object 转换成字符串
	 * @param object
	 * @return
	 */
	public static String toJSONString(Object object) {
		return JSON.toJSONString(object, config);
	}

	public static Object toBean(String text) {
		return JSON.parse(text);
	}
	
	
	 /**  
     * json字符串转化为map  
     * @param s  
     * @return  
     */  
    public static Map stringToCollect(String s) {  
        Map m = JSONObject.parseObject(s);  
        return m;  
    }  
      
    /**  
     * 将map转化为string  
     * @param m  
     * @return  
     */  
    public static String collectToString(Map m) {  
        String s = JSONObject.toJSONString(m);  
        return s;  
    }  

	/**
	 * 用fastjson 将json字符串解析为一个 JavaBean
	 * 
	 * @param jsonString
	 * @param cls
	 * @return
	 */
	public static <T> T getJson(String jsonString, Class<T> cls) {
		T t = null;
		try {
			t = JSON.parseObject(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 用fastjson 将json字符串 解析成为一个 List<JavaBean> 及 List<String>
	 * 
	 * @param jsonString
	 * @param cls
	 * @return
	 */
	public static <T> List<T> getArrayJson(String jsonString, Class<T> cls) {
		List<T> list = new ArrayList<T>();
		try {
			list = JSON.parseArray(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 用fastjson 将json字符串 解析成为一个 List<JavaBean> 及 List<String>
	 * 
	 * @param jsonString
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> getArrayJson(String jsonString) {
		List<T> list = new ArrayList<T>();
		try {
			list = (List<T>) JSON.parseArray(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 用fastjson 将jsonString 解析成 List<Map<String,Object>>
	 * 
	 * @param jsonString
	 * @return
	 */
	public static List<Map<String, Object>> getListMap(String jsonString) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			// 两种写法
			// list = JSON.parseObject(jsonString, new
			// TypeReference<List<Map<String, Object>>>(){}.getType());

			list = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() {
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}

测试

public class Test  {
	
	public static Map<String, String> params= new HashMap<String, String>();
	
	static {
		params.put("userId", "123456");		
		params.put("userName", "zhangsan");
		params.put("age","14");
		params.put("score","90");	
	}	
	
	public static void main(String[] args) {		
		
		//普通的 x-www-form-urlencoded 请求,返回对象
		String url="";
		NewsVO newsVO=HttpClientVOUtils.postFormVO(url,params,NewsVO.class);
		System.out.println(newsVO);		
		
		//application/json请求,返回对象
		String url2="";
		String paramsData=FastJsonTools.toJSONString(params);
		NewsVO newsVO2=HttpClientVOUtils.postJsonVO(url2, paramsData, NewsVO.class);
		System.out.println(newsVO2);
	}	
}
展开阅读全文

没有更多推荐了,返回首页