SpringBoot 封装Http请求

7 篇文章 0 订阅

1.引入jar包

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.10</version>
        </dependency>

2.HttpUtils操作类封装

package com.gnss.gis.utils;

import com.gnss.gis.model.http.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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 java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Http Request Tool Class
 * @author Mr.Li
 * @date 2022-12-09
 */
@Slf4j
public class HttpUtils {
    private HttpUtils() {
    }

    private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    /**
     * Send Http Post Request
     * @param url
     * @param paramsJson
     * @param headsMap
     * @return
     * @throws IOException
     */
    public static HttpResult httpPost(String url, String paramsJson, Map<String, String> headsMap) throws IOException {
        HttpResult httpResult = new HttpResult();
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000)
                    .setSocketTimeout(3000).setConnectTimeout(3000).build();
            httpPost.setConfig(config);
            if (headsMap != null && !headsMap.isEmpty()) {
                headsMap.forEach((key, value) -> {
                    httpPost.addHeader(key, value);
                });
            }else{
                headsMap=new HashMap<>();
            }
            if (headsMap.containsKey("Content-type")) {
                httpPost.addHeader("Content-type", "application/json;charset=utf-8");
            }
            StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity result = response.getEntity();
                String resultStr = null;
                if (result != null) {
                    resultStr = EntityUtils.toString(result, "UTF-8");
                }
                httpClient.close();
                response.close();
                httpResult.setStatus(HttpStatus.SC_OK);
                httpResult.setResult(resultStr);
                return httpResult;
            } else {
                httpResult.setStatus(response.getStatusLine().getStatusCode());
                httpResult.setResult("");
                return httpResult;
            }
        }catch (Exception ex) {
            httpResult.setStatus(HttpStatus.SC_NOT_FOUND);
            httpResult.setResult(ex.getMessage());
            return httpResult;
        }
    }

    /**
     * For get requests without parameters, if the status code is 200, the system returns the body. If the status code is not 200, the system returns null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String httpGet(String url,Map<String,String> headerMap) {
        try {
            HttpGet httpGet = new HttpGet(url);
            for(String key:headerMap.keySet()) {
                httpGet.addHeader(key,headerMap.get(key));
            }
            RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000)
                    .setSocketTimeout(3000).setConnectTimeout(3000).build();
            httpGet.setConfig(config);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if(response!=null) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }else {
                return null;
            }
        }catch (Exception e) {
            return null;
        }
    }
}

Http请求应答结果实体类

package com.gnss.gis.model.http;

import lombok.Data;

/**
 * Http 应答
 * @author Mr.Li
 * @date 2022-07-27
 */
@Data
public class HttpResult {
    private Integer status;
    private String result;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鱼>

一分也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值