HTTPClient在Springboot中封装的工具类

1. 添加依赖项

<!-- 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>

2. 封装工具类

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;
        }
    }
}
在使用Spring Boot封装HttpClient时,可以使用Apache HttpClient库。以下是一个简单的封装示例: 1. 添加依赖 首先,在Maven或Gradle项目的构建文件添加Apache HttpClient的依赖: Maven: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` Gradle: ```groovy implementation 'org.apache.httpcomponents:httpclient:4.5.13' ``` 2. 创建Http请求封装类 创建一个名为HttpClientUtil的Java类,用于封装HttpClient的常用操作: ```java import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; 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.methods.HttpRequestBase; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { private CloseableHttpClient httpClient; public HttpClientUtil() { httpClient = HttpClientBuilder.create().build(); } public String doGet(String url) throws IOException { HttpGet request = new HttpGet(url); return executeRequest(request); } public String doPost(String url, Map<String, String> params) throws IOException { HttpPost request = new HttpPost(url); if (params != null && !params.isEmpty()) { List<NameValuePair> nameValuePairs = new ArrayList<>(); for (Map.Entry<String, String> entry : params.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } return executeRequest(request); } private String executeRequest(HttpRequestBase request) throws IOException { try (CloseableHttpResponse response = httpClient.execute(request)) { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } return null; } } ``` 3. 使用封装类 现在,你可以在Spring Boot的任何组件使用HttpClientUtil类进行HTTP请求。例如,在一个Controller使用: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { private HttpClientUtil httpClientUtil; public MyController(HttpClientUtil httpClientUtil) { this.httpClientUtil = httpClientUtil; } @GetMapping("/api/request") public String makeRequest() { try { String response = httpClientUtil.doGet("https://example.com"); return response; } catch (IOException e) { e.printStackTrace(); return "Error"; } } } ``` 以上示例演示了如何封装HttpClient并在Spring Boot应用程序使用它进行GET请求。你可以根据自己的需求,进一步扩展封装类,支持更多的HTTP方法和功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值