SpringBoot使用RestTemplate访问第三方接口工具类

restTemplate工具

package com.intellsite.common.core.utils;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author: qts
 *  解决乱码问题
 */
public class RestTemplateUtil {
    private static final RestTemplate restTemplate = new RestTemplate();

    private RestTemplateUtil() {
    }

    public static RestTemplate getInstance() {
        //-----此处是 解决乱码 start-----
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        //移除StringHttpMessageConverter
        converterList.remove(1);
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        //convert顺序错误会导致失败
        converterList.add(1, converter);
//        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//        converterList.add(fastJsonHttpMessageConverter);
        restTemplate.setMessageConverters(converterList);
        //-----此处是  解决乱码 end----------
        return restTemplate;
    }
}

get和post和delete请求

package com.intellsite.im.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.intellsite.common.core.utils.RestTemplateUtil;
import com.intellsite.im.IMConstants;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * desc: IM rest Api 请求工具
 *
 * @author qts
 * @date 2021/12/3 0003 上午 11:09
 */
public class IMRestUtil {

    private static final RestTemplate restTemplate = RestTemplateUtil.getInstance();

    /**
     * im post 请求
     * @param contentType
     * @param params 请求参数
     * @param modelUrl 模块url
     * @return
     */
    public static JSONObject imPost(String contentType, Map<String, Object> params, String modelUrl) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-LC-Id", IMConstants.APP_ID);
        headers.add("X-LC-Key", IMConstants.MASTER_KEY+",master");
        if (StrUtil.isNotEmpty(contentType)) {
            headers.add("Content-Type", contentType);
        }

        //MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(params, headers);
        //String urlParams = url + "?params={json}";
        ResponseEntity<String> responseEntity = restTemplate.exchange(IMConstants.SERVER_URL+modelUrl, HttpMethod.POST, httpEntity, String.class);
        return JSON.parseObject(responseEntity.getBody());
    }

    /**
     * im get 请求
     * @param contentType
     * @param params 请求参数,没有参数,随便传一个
     * @param modelUrl 模块url
     * @return
     */
    public static String imGet(String contentType, Map<String, Object> params, String modelUrl) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-LC-Id", IMConstants.APP_ID);
        headers.add("X-LC-Key", IMConstants.MASTER_KEY+",master");
        if (StrUtil.isNotEmpty(contentType)) {
            headers.add("Content-Type", contentType);
        }

        //MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(null, headers);
        //String urlParams = url + "?params={json}";
        ResponseEntity<String> responseEntity;
        if (params == null) {
            responseEntity = restTemplate.exchange(IMConstants.SERVER_URL + modelUrl, HttpMethod.GET, httpEntity, String.class);
        } else {
            responseEntity = restTemplate.exchange(IMConstants.SERVER_URL+modelUrl, HttpMethod.GET, httpEntity, String.class,params);
        }
        return responseEntity.getBody();
    }
}

/**
 * im delete 请求
 * @param contentType
 * @param params 请求参数,非必传
 * @param modelUrl 模块url
 * @return
 */
public static String imDelete(String contentType, Map<String, Object> params, String modelUrl) {
    // header参数
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-LC-Id", IMConstants.APP_ID);
    headers.add("X-LC-Key", IMConstants.MASTER_KEY+",master");
    if (StrUtil.isNotEmpty(contentType)) {
        headers.add("Content-Type", contentType);
    }

    //MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    HttpEntity<Object> httpEntity = new HttpEntity<Object>(null, headers);
    //String urlParams = url + "?params={json}";
    ResponseEntity<String> responseEntity;
    if (params == null) {
        responseEntity = restTemplate.exchange(IMConstants.SERVER_URL + modelUrl, HttpMethod.DELETE, httpEntity, String.class);
    } else {
        responseEntity = restTemplate.exchange(IMConstants.SERVER_URL+modelUrl, HttpMethod.DELETE, httpEntity, String.class,params);
    }
    return responseEntity.getBody();
}

测试案例

发送get请求:  后面拼接参数的方式
// 请求参数
Map<String, Object> params = new HashMap<String, Object>();
        params.put("skip",conversation.getSkip() );// 跳过几条数据
        params.put("limit",conversation.getLimit() );// 条数
        params.put("where", "{\"m\":\""+conversation.getMembers().get(0)+"\"}");// 指定成员ID
        params.put("order","-createdAt" );// 创建时间倒序
String jsonStr = IMRestUtil.imGet(null, params, "请求的url"+"?skip={skip}&limit={limit}&where={where}&order={order}");
        
发送post请求
// 请求参数
Map<String, Object> params = new HashMap<String, Object>();
        params.put("name",conversation.getName() );
        params.put("m",conversation.getMembers() );
        params.put("unique",conversation.getUnique() );
        params.put("attr",conversation.getAttributes() );
JSONObject jsonObject = IMRestUtil.imPost(ContentType.JSON.getValue(), params, "请求的url");
// 请求参数
Map<String, Object> params = new HashMap<String, Object>();
params.put("conversationId",conversationId );
String resultJson = IMRestUtil.imDelete(null, params, "请求的url" + "/{conversationId}");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot项目中使用RestTemplate可以方便地进行HTTP请求。你可以通过创建RestTemplate实例来使用它。在你提供的代码中,你展示了两种使用RestTemplate的方式。 第一种方式是通过自己创建RestTemplate实例并设置连接超时和读取超时的方式。你可以使用SimpleClientHttpRequestFactory来设置连接超时和读取超时的时间,然后将其设置为RestTemplate的请求工厂。这样就可以创建一个自定义配置的RestTemplate实例。 第二种方式是通过使用注解@Autowired将RestTemplate实例注入到你的代码中。这种方式需要在Spring Boot项目中配置RestTemplate的Bean,然后使用@Autowired注解将其注入到需要使用的地方。 RestTemplate提供了多种方法来发送HTTP请求,包括GET请求、POST请求、PUT请求、DELETE请求等。你可以根据需要选择合适的方法来发送请求。在你提供的代码中,展示了使用postForObject方法发送POST请求的示例。你可以指定请求的URL、请求的参数和返回结果的类型,然后使用postForObject方法发送请求并获取返回结果。 总之,Spring Boot中的RestTemplate是一个方便的HTTP请求工具,可以帮助你发送各种类型的HTTP请求。你可以根据需要选择合适的方式来使用RestTemplate。 #### 引用[.reference_title] - *1* [Springboot 使用RestTemplate](https://blog.csdn.net/qq_30938705/article/details/109804221)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot使用RestTemplate](https://blog.csdn.net/watson2017/article/details/124865399)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值