自学内容网 自学内容网

Springboot实现调用接口(使用RestTemplate)

一、在启动类配置RestTemplate

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

二、引入json的依赖(获取response body可以用到)

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

三、依赖注入

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;

四、调接口

String url = "";
//设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("honeycombToken", "");
//设置请求体
HashMap<String, String> map = new HashMap<>();
map.put("", "");
map.put("", "");
// 将请求头和请求体封装到HttpEntity中
HttpEntity<HashMap<String, String>> hashMapHttpEntity = new HttpEntity<>(map,httpHeaders);
//发送post请求
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, hashMapHttpEntity, String.class);
// 将返回的JSON字符串解析为JsonNode对象
JsonNode jsonNode = objectMapper.readTree(response.getBody());
//获取指定的字段名token
String token = jsonNode.get("data").get("token").toString();

原文地址:https://blog.csdn.net/m0_73463767/article/details/144400996

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!