package com.googosoft.until; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; 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.JSONArray; import com.googosoft.model.HttpClientResult; /** * @author songyan * @version 2020年1月13日 下午1:57:15 * @desc HttpClient发送http请求工具类 */ public class HttpClientUtil { protected static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); /** * 发送无参get请求 * @param url * @return * @throws ClientProtocolException * @throws IOException */ public static HttpClientResult sendGetRequest(String url){ HttpClientResult result = new HttpClientResult(); CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(url); CloseableHttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); result.setContent(content); result.setCode(response.getStatusLine().getStatusCode()); } catch (ClientProtocolException e) { logger.error("协议异常,堆栈信息如下", e); } catch (IOException e) { logger.error("网络异常,堆栈信息如下", e); } finally { try { client.close(); } catch (Exception e) { e.printStackTrace(); client = null; } } return result; } /** * 发送无参put请求 * @param url * @return */ public static HttpClientResult sendPutReq(String url) { HttpClientResult result = new HttpClientResult(); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPut put = new HttpPut(url); try { HttpResponse httpResponse = httpClient.execute(put); if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity = httpResponse.getEntity(); String content = EntityUtils.toString(entity); result.setContent(content); }else{ result.setCode(httpResponse.getStatusLine().getStatusCode()); } } catch (ClientProtocolException e) { logger.error("协议异常,堆栈信息如下", e); } catch (IOException e) { logger.error("网络异常,堆栈信息如下", e); } finally { try { httpClient.close(); } catch (Exception e) { e.printStackTrace(); httpClient = null; } } return result; } public static JSONArray StrToJsonArray(String content) { return null; } }