java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > HTTPClient在Springboot中封装工具类

HTTPClient如何在Springboot中封装工具类

作者:屿麟

这篇文章主要介绍了HTTPClient如何在Springboot中封装工具类问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

HTTPClient在Springboot中封装工具类

添加依赖项

<!-- lombok常用工具集 -->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>
<!-- hutool常用工具集 -->
<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>4.1.0</version>
</dependency>
<!-- fastjson工具集 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.59</version>
</dependency>

封装工具类

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
 * 基于httpclient封装的http请求类,支持put/get/post
 *
 * @author leizhigang
 * @date 2020-07-09
 */
@Slf4j
public class YesHttpUtil {
    /**
     * 封装httpRequest Get方法
     *
     * @param url
     * @param object
     * @return JsonObject
     */
    public String httpRequestGet (String url, Map<String,Object> paramsMap, Integer connectionTimeout) {
        try {
            HttpResponse response = HttpRequest.get(url)
                    .form(paramsMap)
                    .timeout(connectionTimeout)
                    .execute();
            if(response.getStatus() == 200) {
                String result = response.body();
                //JSONObject jsonResult = JSON.parseObject(result);
                return result;
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String errTime = dateFormat.format(new Date());
                log.error(errTime + "  response error(" + response.getStatus() + "):" + url);
                return null;
            }
        } catch (Exception ex) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String errTime = dateFormat.format(new Date());
            log.error(errTime + "  request shell CRM error: " + ex.getMessage());
            return null;
        }
    }
    /**
     * 封装httpRequest Post方法
     *
     * @param url
     * @param object
     * @return JsonObject
     */
    public JSONObject httpRequestPost (String url, String jsonBody,  Integer connectionTimeout) {
        try {
            // 向壳牌CRM发起请求,使用cn.hutool.http.HttpRequest,返回对象为cn.hutool.http.HttpResponse
            HttpResponse response = HttpRequest.post(url)
                    .contentType("application/json")
                    .timeout(connectionTimeout)
                    .body(jsonBody)
                    .execute();
            // 判断请求状态是否正常
            if(response.getStatus() == 200) {
                String result = response.body();
                com.alibaba.fastjson.JSONObject jsonResult = JSON.parseObject(result);
                return jsonResult;
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String errTime = dateFormat.format(new Date());
                log.error(errTime + "  response error(" + response.getStatus() + "):" + url);
                return null;
            }
        } catch (Exception ex){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String errTime = dateFormat.format(new Date());
            log.error(errTime + "  request shell CRM error: " + ex.getMessage());
            return null;
        }
    }
    /**
     * 封装httpRequest Put方法
     *
     * @param url
     * @param object
     * @return JsonObject
     */
    public JSONObject httpRequestPut (String url, String jsonBody,  Integer connectionTimeout) {
        try {
            // 向壳牌CRM发起请求,使用cn.hutool.http.HttpRequest,返回对象为cn.hutool.http.HttpResponse
            HttpResponse response = HttpRequest.put(url)
                    .contentType("application/json")
                    .timeout(connectionTimeout)
                    .body(jsonBody)
                    .execute();
            // 判断请求状态是否正常
            if(response.getStatus() == 200) {
                String result = response.body();
                com.alibaba.fastjson.JSONObject jsonResult = JSON.parseObject(result);
                return jsonResult;
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String errTime = dateFormat.format(new Date());
                log.error(errTime + "  response error(" + response.getStatus() + "):" + url);
                return null;
            }
        } catch (Exception ex){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String errTime = dateFormat.format(new Date());
            log.error(errTime + "  request shell CRM error: " + ex.getMessage());
            return null;
        }
    }
    /**
     * 自定义httpPost方法,使用org.apache.http.client实现
     * 问题:请求超时,无法通过VPN请求接口,需进一步调试
     *
     * @param url
     * @param object
     * @return JsonObject
     */
    public static Object httpClientPost(String url, Object object, Integer connectionTimeout, Integer connectionRequestTimeout, Integer socketTimeout) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求的Config
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);
        // 设置请求的header
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        // 设置请求的body
        // JSONObject jsonParam = JSONObject.parseObject(JSONObject.toJSONString(registerMemberParam));
        String jsonString = JSONObject.toJSONString(object);
        StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
        // StringEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        // 执行请求
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            System.out.println("得到的结果:" + response.getStatusLine());//得到请求结果
            HttpEntity entityResult = response.getEntity();//得到请求回来的数据
            // 解析返回结果
            String result = EntityUtils.toString(entityResult, "utf-8");
            JSONObject jsonObject = JSONObject.parseObject(result);
            // 打印执行结果
            System.out.println(jsonObject);
            return jsonObject;
        } catch (Exception ex) {
            System.out.println("发送 POST 请求出现异常!" + ex);
            ex.printStackTrace();
            return null;
        }
    }
}

httpclient封装工具类方式

在日常开发中,我们经常需要通过http协议去调用网络内容,虽然java自身提供了net相关工具包,但是其灵活性和功能总是不如人意,于是有人专门搞出一个httpclient类库,来方便进行Http操作。

对于httpcore的源码研究,我们可能并没有达到这种层次,在日常开发中也只是需要的时候,在网上百度一下,然后进行调用就行。

在项目中对于这个工具类库也许没有进行很好的封装。

在哪里使用就写在哪些,很多地方用到,就在多个地方写。反正是复制粘贴,很方便,但是这样就会导致项目中代码冗余。

所以这里简单的对httpcient的简单操作封装成一个工具类,统一放在项目的工具包中,在使用的时候直接从工具包中调用,不需要写冗余代码。

httpclient操作实例

首先需要在注意的一点是,这是基于httpclient4.5版本的,我们在使用的时候需要引入具体对应jar。

下面是具体代码示例

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.conn.ssl.SSLConnectionSocketFactory;
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.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
/**
 * 基于 httpclient 4.5版本的 http工具类
 * 
 * @author 爱琴孩
 * 
 */
public class HttpClientTool {
	private static final CloseableHttpClient httpClient;
	public static final String CHARSET = "UTF-8";
	// 采用静态代码块,初始化超时时间配置,再根据配置生成默认httpClient对象
	static {
		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	}
	public static String doGet(String url, Map<String, String> params) {
		return doGet(url, params, CHARSET);
	}
	public static String doGetSSL(String url, Map<String, String> params) {
		return doGetSSL(url, params, CHARSET);
	}
	public static String doPost(String url, Map<String, String> params) throws IOException {
		return doPost(url, params, CHARSET);
	}
	/**
	 * HTTP Get 获取内容
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset 编码格式
	 * @return 页面内容
	 */
	public static String doGet(String url, Map<String, String> params, String charset) {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				// 将请求参数和url进行拼接
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * HTTP Post 获取内容
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset 编码格式
	 * @return 页面内容
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params, String charset) 
			throws IOException {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		List<NameValuePair> pairs = null;
		if (params != null && !params.isEmpty()) {
			pairs = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				String value = entry.getValue();
				if (value != null) {
					pairs.add(new BasicNameValuePair(entry.getKey(), value));
				}
			}
		}
		HttpPost httpPost = new HttpPost(url);
		if (pairs != null && pairs.size() > 0) {
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
		}
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			return result;
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			if (response != null)
				response.close();
		}
		return null;
	}
	/**
	 * HTTPS Get 获取内容
	 * @param url 请求的url地址 ?之前的地址
	 * @param params 请求的参数
	 * @param charset  编码格式
	 * @return 页面内容
	 */
	public static String doGetSSL(String url, Map<String, String> params, String charset) {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpGet httpGet = new HttpGet(url);
			// https  注意这里获取https内容,使用了忽略证书的方式,当然还有其他的方式来获取https内容
			CloseableHttpClient httpsClient = HttpClientTool.createSSLClientDefault();
			CloseableHttpResponse response = httpsClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 这里创建了忽略整数验证的CloseableHttpClient对象
	 * @return
	 */
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
}

上面就是对于httpclient的简单工具类,对于httpclient,还有很多知识点需要仔细研究。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文