Http请求简单工具类
Http请求简单工具类
import java.io.IOException; import java.util.Map; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; 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.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; /** * Http请求工具类 */ public class HttpRequestUtil { private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class); /** * 发送带map参数的get请求,返回一个T类型的参数 */ public static <T> T getForObject(String url, Map<String, String> params, Class<T> tClass) { logger.info("getForObject start. url:{},tClass:{}", url,tClass); String httpResult = doGet(url,params); if(StringUtils.isBlank(httpResult)){ logger.warn("httpResult is empty"); return null; } JSONObject jsonObject = JSONObject.parseObject(httpResult); T rsp = JSON.toJavaObject(jsonObject,tClass); logger.info("getForObject end,rsp:{}",httpResult); return rsp; } /** * 发送 get请求,K-V形式 * @param url * @param params * @author Charlie.chen */ private static String doGet(String url,Map<String, String> params) { String apiUrl = url; if (params != null) { StringBuffer param = new StringBuffer(); int i = 0; for (String key : params.keySet()) { if (i == 0) { param.append("?"); }else { param.append("&"); } param.append(key).append("=").append(params.get(key)); i++; } apiUrl += param; } return doGet(apiUrl); } /** * 发送GET请求(HTTP),不传入参数 */ private static String doGet(String url) { logger.info("doGet start. url:{}",url); // 创建默认的HttpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = null; CloseableHttpResponse httpResponse = null; try { RequestConfig config = null; if (StringUtils.isNotEmpty(Constants.PROXY_IP) && Constants.PROXY_PORT > 0) { // 依次是代理地址,代理端口号,协议类型 String agreement = url.substring(0, url.indexOf(":")); HttpHost proxy = new HttpHost(Constants.PROXY_IP, Constants.PROXY_PORT, agreement); config = RequestConfig.custom().setProxy(proxy).build(); } // 定义一个get请求方法 httpget = new HttpGet(url); if(config != null) { httpget.setConfig(config); } // 执行get请求,返回response服务器响应对象, 其中包含了状态信息和服务器返回的数据 httpResponse = httpclient.execute(httpget); // 使用响应对象, 获得状态码, 处理内容 int statusCode = httpResponse.getStatusLine().getStatusCode(); String result = ""; if (statusCode >= 200 && statusCode < 300) { // 使用响应对象获取响应实体 HttpEntity entity = httpResponse.getEntity(); if (entity != null) { // 将响应实体转为字符串 result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); logger.info("doGet result : " + result); } }else { logger.warn("doGet fail,statusCode:{}",statusCode); } EntityUtils.consume(httpResponse.getEntity()); httpResponse.close(); return result; } catch (Exception e) { logger.warn("doGet fail. statusCode",e); } finally { if(httpget != null) { httpget.releaseConnection(); } if (httpResponse != null) { try { EntityUtils.consume(httpResponse.getEntity()); httpResponse.close(); } catch (IOException e) { logger.error("doGet consume fail : ",e); } } } return null; } /** * post请求 * @param url * @param json * @return */ public static String httpPost(String url, String jsonStr) { String result = null; // 创建HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // HttpClient CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); try { // 依次是目标请求地址,端口号,协议类型 // HttpHost target = new HttpHost("10.10.100.102:8080/mytest", 8080, "https"); RequestConfig config = null; if (StringUtils.isNotEmpty(Constants.PROXY_IP) && Constants.PROXY_PORT > 0) { // 依次是代理地址,代理端口号,协议类型 String agreement = url.substring(0, url.indexOf(":")); HttpHost proxy = new HttpHost(Constants.PROXY_IP, Constants.PROXY_PORT, agreement); config = RequestConfig.custom().setProxy(proxy).build(); } // 请求地址 HttpPost httpPost = new HttpPost(url); if(config != null) { httpPost.setConfig(config); } StringEntity s = new StringEntity(jsonStr); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//发送json数据需要设置contentType httpPost.setEntity(s); HttpResponse response = closeableHttpClient.execute(httpPost); // CloseableHttpResponse response = closeableHttpClient.execute(target, httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = response.getEntity(); if(httpEntity != null) { result = EntityUtils.toString(httpEntity);// 返回json格式 logger.info("result:{}", result); } } }catch(Exception e) { logger.warn("doPost请求异常,e:{}", e); }finally { // 释放资源 try { if(closeableHttpClient != null) { closeableHttpClient.close(); } } catch (IOException e) { logger.warn("关闭CloseableHttpClient异常,e:{}", e); } finally { closeableHttpClient = null; } } return result; } }
posted on 2018-02-22 21:46 bijian1013 阅读(176) 评论(0) 收藏 举报
浙公网安备 33010602011771号