100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 封装Apache http client工具类

封装Apache http client工具类

时间:2022-07-26 19:58:36

相关推荐

封装Apache http client工具类

一,maven需要的配置

<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.7</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.58</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency>

如果对日志有自己的需求,可根据实际情况添加自己需要的日志依赖。

二,封装Apache http client工具类

package com.jingjin.socket.util;import com.alibaba.fastjson.JSONObject;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.config.RequestConfig;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.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.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.slf4j.LoggerFactory;import java.io.IOException;import java.io.UnsupportedEncodingException;import .URI;import .URISyntaxException;import java.util.ArrayList;import java.util.List;import java.util.Map;//http调用工具类public class HttpClientUtil {private static org.slf4j.Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);private static final int DEFULT_TIMEOUT = 30 * 1000;//默认超时时间20秒/*** 调用http get请求* @param url* @param params* @return*/public static String doGet(String url, Map<String, Object> params) {return doGet(url, null, params, null);}/*** 调用http get请求* @param url* @param params* @param timeout* @return*/public static String doGet(String url,Map<String,Object> params,Integer timeout){return doGet(url, null, params, timeout);}/**** @param url* @param headers* @param params* @param timeout* @return*/private static String doGet(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) {//创建httpClient对象CloseableHttpClient httpClient = HttpClients.createDefault();String resultString = null;CloseableHttpResponse response = null;try {//创建uriURIBuilder builder = new URIBuilder(url);if (params != null) {//uri添加参数for (String key : params.keySet()) {builder.addParameter(key, String.valueOf(params.get(key)));}}URI uri = builder.build();//创建hTTP get请求HttpGet httpGet = new HttpGet(uri);//设置超时时间int timeoutTmp = DEFULT_TIMEOUT;if (timeout != null) {timeoutTmp = timeout;}RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp).setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();httpGet.setConfig(requestConfig);//设置头信息if(null!=headers){for (String key:headers.keySet()) {httpGet.setHeader(key,headers.get(key));}}//执行请求response=httpClient.execute(httpGet);if (HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){resultString= EntityUtils.toString(response.getEntity(), Consts.UTF_8);}} catch (URISyntaxException e) {logger.error("http调用异常" + e.toString(), e);}catch (IOException e){logger.error("http调用异常" + e.toString(), e);}finally {try {if(null!=response){response.close();}}catch (IOException e){logger.error("response关闭异常" + e.toString(), e);}try {if(null!=httpClient){httpClient.close();}}catch (IOException e){logger.error("httpClient关闭异常" + e.toString(), e);}}return resultString;}/*** 调用http post请求(json数据)* @param url* @param json* @return*/public static JSONObject doJsonPost(String url,JSONObject json){CloseableHttpClient httpClient = HttpClientBuilder.create().build();HttpPost post = new HttpPost(url);CloseableHttpResponse httpResponse=null;JSONObject response=null;try {StringEntity s = new StringEntity(json.toString(), Consts.UTF_8);s.setContentType("application/json");//发送json数据需要设置的contentTypepost.setEntity(s);httpResponse=httpClient.execute(post);if (httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){String result=EntityUtils.toString(httpResponse.getEntity());//返回json格式response=JSONObject.parseObject(result);}}catch (Exception e){throw new RuntimeException(e);}finally {try {if (httpResponse!=null){httpResponse.close();}}catch (IOException e){logger.error("关闭httpResponse异常"+e.toString(),e);}try {if (httpClient!=null){httpClient.close();}}catch (IOException e){logger.error("关闭httpResponse异常"+e.toString(),e);}}return response;}/*** post请求* @param url* @param params* @return*/public static String doPost(String url,Map<String,Object> params){return doPost(url,null,params,null);}/*** post请求 带时间* @param url* @param params* @param timeout* @return*/public static String doPost(String url,Map<String,Object> params,Integer timeout){return doPost(url,null,params,timeout);}/*** 调用http post请求 基础方法* @param url 请求的url* @param headers 请求头* @param params 参数* @param timeout 超时时间* @return*/public static String doPost(String url,Map<String,String> headers,Map<String,Object> params,Integer timeout){CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response=null;String resultString="";try {//创建http post请求HttpPost httpPost = new HttpPost(url);//设置超时时间int timeoutTmp=DEFULT_TIMEOUT;if (timeout!=null){timeoutTmp=timeout;}RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp).setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();httpPost.setConfig(requestConfig);//设置参数信息if (params!=null){List<NameValuePair> paramList=new ArrayList<>();for (String key:params.keySet()) {paramList.add(new BasicNameValuePair(key,String.valueOf(params.get(key))));}//模拟表单UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);httpPost.setEntity(entity);}//设置头信息if (headers!=null){for (String key:headers.keySet()) {httpPost.setHeader(key,headers.get(key));}}//执行http请求response=httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){resultString=EntityUtils.toString(response.getEntity(),Consts.UTF_8);}}catch (UnsupportedEncodingException e){logger.error("调用http异常"+e.toString(),e);}catch (ClientProtocolException e){logger.error("调用http异常"+e.toString(),e);}catch (IOException e){logger.error("调用http异常"+e.toString(),e);}finally {try {if (null != response) {response.close();}} catch (IOException e) {logger.error("关闭response异常"+e.toString(),e);}try {if (null != httpClient) {httpClient.close();}} catch (IOException e) {logger.error("关闭httpClient异常"+e.toString(),e);}}return resultString;}}

可以使用当前工具进行远程http调用,支持post和get。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。