如何设计通用的处理HTTP接口的工具类

关注我,升职加薪就是你!
下面的类添加了接口请求Header中的入参处理,请求Body中的入参处理,以及GET请求方式的入参处理。话不多说,直接上代码。

package com.demo.common.http;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.demo.common.utils.DataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Author: Max
 * @Date: 2023/2/1
 * @Description: 调用HTTP接口的工具类
 * @Version: v1.0
 */
@Slf4j
public class HttpHelper {

    private static final int OK = 200;

    /**
     * GET请求
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String sendGet(String apiUrl, String paramStr)  {
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiUrl,String.class,paramStr);
        return responseEntity.getBody();
    }

    private static void setUtf8(RestTemplate restTemplate){
        if (null == restTemplate || ObjectUtils.isEmpty(restTemplate.getMessageConverters())) {
            return;
        }
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        for (int i = 0; i < messageConverters.size(); i++) {
            HttpMessageConverter<?> httpMessageConverter = messageConverters.get(i);
            if (httpMessageConverter.getClass().equals(StringHttpMessageConverter.class)) {
                messageConverters.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            }
        }

    }

    /**
     * GET请求
     *
     * @param apiUrl
     * @param apiUsername
     * @param apiPassword
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String sendGet(String apiUrl, String apiUsername, String apiPassword, String paramStr) throws Exception {
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        if(StringUtils.isNotBlank(apiUsername) && StringUtils.isNotBlank(apiPassword)){
            restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(apiUsername,apiPassword));
        }
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiUrl,String.class,paramStr);
        return responseEntity.getBody();
    }
    /**
     * POST请求
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String sendPost(String apiUrl, String paramStr) {
        return sendPostWithHeader(apiUrl,paramStr,null);
    }

    /**
     * POST请求
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String sendPostAndToken(String apiUrl, String paramStr, String token) {
        return sendPostWithHeaderAndToken(apiUrl,paramStr,null,token);
    }


    /**
     * POST请求,需要设置header的时候调用
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String sendPostWithHeaderAndToken(String apiUrl, String paramStr, Map<String,Object> headerMap, String token) {
        HttpHeaders headers = new HttpHeaders();
        if(DataUtil.isNotEmpty(headers)){
            Iterator<Map.Entry<String,Object>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String,Object> entry =  it.next();
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        }else{
            headers.add("content-type","application/json;charset=UTF-8");
        }
        headers.add("Authorization",token);
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<String>(paramStr,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST,httpEntity,String.class);
        return responseEntity.getBody();
    }

    /**
     * POST请求,需要设置header的时候调用
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String sendPostWithHeader(String apiUrl, String paramStr, Map<String,Object> headerMap) {
        HttpHeaders headers = new HttpHeaders();
        if(DataUtil.isNotEmpty(headers)){
            Iterator<Map.Entry<String,Object>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String,Object> entry =  it.next();
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        }else{
            headers.add("content-type","application/json;charset=UTF-8");
        }
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<String>(paramStr,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST,httpEntity,String.class);
        return responseEntity.getBody();
    }

    /**
     * POST请求
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static JSONObject sendPostWithToken(String apiUrl, String paramStr, String token) {
        return sendPostWithToken(apiUrl,paramStr,null,token);
    }


    /**
     * POST请求,需要设置header的时候调用
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static JSONObject sendPostWithToken(String apiUrl, String paramStr, Map<String,Object> headerMap, String token) {
        HttpHeaders headers = new HttpHeaders();
        if(DataUtil.isNotEmpty(headers)){
            Iterator<Map.Entry<String,Object>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String,Object> entry =  it.next();
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        }else{
            headers.add("content-type","application/json;charset=UTF-8");
        }
        headers.add("token",token);
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<String>(paramStr,headers);
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST,httpEntity,JSONObject.class);
        return responseEntity.getBody();
    }
    /**
     * POST请求,需要设置header的时候调用
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static JSONObject sendPostGetObject(String apiUrl, String paramStr, Map<String,Object> headerMap) {
        HttpHeaders headers = new HttpHeaders();
        if(DataUtil.isNotEmpty(headers)){
            Iterator<Map.Entry<String,Object>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String,Object> entry =  it.next();
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        }else{
            headers.add("content-type","application/json;charset=UTF-8");
        }
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<String>(paramStr,headers);
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST,httpEntity,JSONObject.class);
        return responseEntity.getBody();
    }


    /**
     * POST请求,ERP中台 工号认证
     *
     * @param apiUrl
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String sendPostWithCode(String apiUrl, String paramStr, Map<String,Object> headerMap, String code) {
        HttpHeaders headers = new HttpHeaders();
        if(DataUtil.isNotEmpty(headers)){
            Iterator<Map.Entry<String,Object>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String,Object> entry =  it.next();
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        }else{
            headers.add("content-type","application/json;charset=UTF-8");
        }
        headers.add("x-pagoda-user-id",code);
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<String>(paramStr,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST,httpEntity,String.class);
        return responseEntity.getBody();
    }

    /**
     * @Author: Max
     * @Date: 2023/1/9
     * @Description: POST请求,需要设置header的时候调用
     * @Param:
     * @param apiUrl
     * @param paramStr
     * @param headerMap
     * @param needHeader
     * @Return: java.lang.String
     */
    public static String sendPostWithHeaders(String apiUrl, String paramStr, Map<String,Object> headerMap, boolean needHeader) {
        HttpHeaders headers = new HttpHeaders();
        if(DataUtil.isNotEmpty(headerMap)){
            Iterator<Map.Entry<String,Object>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String,Object> entry =  it.next();
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        } else {
            if (needHeader) {
                headers.add("content-type","application/json;charset=UTF-8");
            }
        }
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<String>(paramStr,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST,httpEntity,String.class);
        return responseEntity.getBody();
    }

    /**
     * @Author: Max
     * @Date: 2023/1/11
     * @Description: 请求头入参需为Content-Type=application/json;charset=UTF-8
     * @Param:
     * @param apiUrl
     * @param paramStr
     * @param headerMap
     * @Return: java.lang.String
     */
    public static String sendPostWithHeaderContentType(String apiUrl, String paramStr, Map<String,Object> headerMap) {
        HttpHeaders headers = new HttpHeaders();
        if(DataUtil.isNotEmpty(headers)){
            Iterator<Map.Entry<String,Object>> it = headerMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String,Object> entry =  it.next();
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        }else{
            headers.add("Content-Type","application/json;charset=UTF-8");
        }
        RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
        setUtf8(restTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<String>(paramStr,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST,httpEntity,String.class);
        return responseEntity.getBody();
    }

}

关注我,升职加薪就是你!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

徐先生Paul

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值