spring boot RestTemplate 发送get请求的踩坑及解决

 更新时间:2021年08月19日 14:22:57   作者:从不喝茶  
这篇文章主要介绍了spring boot RestTemplate 发送get请求的踩坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

spring boot RestTemplate 发送get请求踩坑

闲话少说,代码说话

RestTemplate 实例

手动实例化,这个我基本不用

RestTemplate restTemplate = new RestTemplate(); 

依赖注入,通常情况下我使用 java.net 包下的类构建的 SimpleClientHttpRequestFactory

@Configuration
public class RestConfiguration {
    @Bean
    @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
    public RestOperations restOperations() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        // 使用 utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为 "ISO-8859-1")
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof StringHttpMessageConverter) {
                iterator.remove();
            }
        }
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }
}

请求地址

get 请求 url 为

http://localhost:8080/test/sendSms?phone=手机号&msg=短信内容

错误使用

@Autowired
private RestOperations restOperations;
public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms";
    Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("phone", "151xxxxxxxx");
    uriVariables.put("msg", "测试短信内容");
    String result = restOperations.getForObject(url, String.class, uriVariables);
}

服务器接收的时候你会发现,接收的该请求时没有参数的

正确使用

@Autowired
private RestOperations restOperations;
public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms?phone={phone}&msg={phone}";
    Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("phone", "151xxxxxxxx");
    uriVariables.put("msg", "测试短信内容");
    String result = restOperations.getForObject(url, String.class, uriVariables);
}

等价于

@Autowired
private RestOperations restOperations;
public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms?phone={phone}&msg={phone}";
    String result = restOperations.getForObject(url, String.class,  "151xxxxxxxx", "测试短信内容");
}

springboot restTemplate访问get,post请求的各种方式

springboot中封装好了访问外部请求的方法类,那就是RestTemplate。下面就简单介绍一下,RestTemplate访问外部请求的方法。

get请求

首先get请求的参数是拼接在url后面的。所以不需要额外添加参数。但是也需要分两种情况。

1、 有请求头

由于 getForEntity() 和 getForObject() 都无法加入请求头。所以需要请求头的连接只能使用 exchange() 来访问。代码如下

public JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            String url = "http://test.api.com?id=123";
            headers.set("Content-Type","application/json");
            HttpEntity<JSONObject> jsonObject= re.exchange(url, HttpMethod.GET,new HttpEntity<>(headers),JSONObject.class);
            log.info("返回:{}",jsonObject.getBody());
            return jsonObject.getBody();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

2、 无请求头

无需请求头的可以用三个方法实现。getForEntity() 和 getForObject() 还有 exchange() 都可以实现。下面讲前两种用的比较多的。

getForEntity()

public JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://api.help.bj.cn/apis/alarm/?id=101020100";
            HttpEntity<JSONObject> jsonObject= re.getForEntity(url,JSONObject.class);
            log.info("返回:{}",jsonObject.getBody());
            return jsonObject.getBody();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

getForObject()

public JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://api.help.bj.cn/apis/alarm/?id=101020100";
            JSONObject jsonObject= re.getForObject(url,JSONObject.class);
            log.info("返回:{}",jsonObject);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

post请求

post请求也分几种情况

1、参数在body的form-data里面

public static JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://localhost:8101/test";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
            loginJson.add("id", "123");
            JSONObject jsonObject= re.postForObject(url,new HttpEntity<>(loginJson,headers),JSONObject.class);
            log.info("返回:{}",jsonObject);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

还可以把 postForObject 换成 postForEntity

2、参数在body的x-www-from-urlencodeed里面

只需要把请求头的setContentType改成下面即可

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
public static JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://localhost:8101/test";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
            loginJson.add("id", "123");
            JSONObject jsonObject= re.postForObject(url,new HttpEntity<>(loginJson,headers),JSONObject.class);
            log.info("返回:{}",jsonObject);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

3、参数在body的raw里面

在这里插入图片描述

 public static JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://localhost:8101/test";
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type","application/json");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id","1");
            JSONObject jsonObject1 = restTemplate
                    .postForObject(url,new HttpEntity<>(jsonObject,headers),JSONObject.class);
            log.info("返回:{}",jsonObject1);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

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

相关文章

  • kafka的消息存储机制和原理分析

    kafka的消息存储机制和原理分析

    这篇文章主要介绍了kafka的消息存储机制和原理,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • SpringBoot项目部署到腾讯云的实现步骤

    SpringBoot项目部署到腾讯云的实现步骤

    本文主要介绍了SpringBoot项目部署到腾讯云的实现步骤,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • java读取xml配置参数代码实例

    java读取xml配置参数代码实例

    这篇文章主要介绍了java读取xml配置参数代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • dom4j从jar包中读取xml文件的方法

    dom4j从jar包中读取xml文件的方法

    这篇文章主要介绍了dom4j从jar包中读取xml文件的方法,需要的朋友可以参考下
    2014-02-02
  • SpringBoot 下的 Static 文件夹打包成前端资源的示例代码

    SpringBoot 下的 Static 文件夹打包成前端资源的示例代码

    这篇文章主要介绍了SpringBoot 下的 Static 文件夹如何打包成前端资源,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • Java集合框架超详细小结

    Java集合框架超详细小结

    Java中提供的一种容器,可以用来存储多个数据。java集合大致可以分为Set,List,Queue和Map四种体系。这篇文章主要介绍了Java集合框架超详细小结,需要的朋友可以参考下
    2021-08-08
  • java8 实现提取集合对象的每个属性

    java8 实现提取集合对象的每个属性

    这篇文章主要介绍了java8 实现提取集合对象的每个属性方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • idea聚合工程搭建过程详解

    idea聚合工程搭建过程详解

    本章主要以order订单服务来远程调用payment支付服务为例,当然这里只是简单的一个远程调用,没有太复杂的逻辑,重点是要掌握的是maven的聚合工程搭建,微服务分模块的思想,每一个步骤我都会详细记录,并且文章下方还提供了git源码地址
    2022-06-06
  • java接口语法以及与类的关系详解

    java接口语法以及与类的关系详解

    接口在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明。一个类通过继承接口的方式,从而来继承接口的抽象方法
    2021-10-10
  • SpringBoot 模板模式实现优惠券逻辑的示例代码

    SpringBoot 模板模式实现优惠券逻辑的示例代码

    这篇文章主要介绍了SpringBoot 模板模式实现优惠券逻辑,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08

最新评论