SpringBoot-RestTemplate实现调用第三方API

本文介绍如何使用 Spring Boot 中的 RestTemplate 调用第三方 API,并通过 GET 和 POST 请求获取及发送 JSON 数据。具体步骤包括:引入 fastjson 依赖,配置 RestTemplate,实现 Controller 层的方法来模拟不同类型的 HTTP 请求。

1. RestTemplate的方式来调用别人的API,将数据转化为json 格式,引入了fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>

2. 编写RestTemlateConfig,配置好相关信息



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

3.编写controller,调用第三方的API,浏览器模拟get请求,postman模拟post请求



import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
public class SpringRestTemplateController {
    @Autowired
    private RestTemplate restTemplate;
    /***********HTTP GET method*************/
    @GetMapping("/testGetApi")
    public String getJson(){
        String url="http://localhost:8089/o2o/getshopbyid?shopId=19";
        //String json =restTemplate.getForObject(url,Object.class);
        ResponseEntity<String> results = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        return json;
    }

    /**********HTTP POST method**************/
    @PostMapping(value = "/testPost")
    public Object postJson(@RequestBody JSONObject param) {
        System.out.println(param.toJSONString());
        param.put("action", "post");
        param.put("username", "tester");
        param.put("pwd", "123456748");
        return param;
    }

    @PostMapping(value = "/testPostApi")
    public Object testPost() {
        String url = "http://localhost:8081/girl/testPost";
        JSONObject postData = new JSONObject();
        postData.put("descp", "request for post");
        JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
        return json;
    }
}

 

在Spring Boot 3中使用`RestTemplate`调用第三方API时,尽管Spring官方推荐使用更现代的`WebClient`进行HTTP请求处理,但`RestTemplate`仍然可用,并且在某些场景下依然具有优势,尤其是在简单请求和同步操作中。 ### 配置RestTemplate Bean 为了在Spring Boot 3中使用`RestTemplate`,首先需要将其配置为一个Bean,以便Spring容器可以管理其生命周期。可以在配置类中定义如下Bean: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ``` ### 调用第三方API的示例 假设需要调用一个返回JSON数据的GET接口,例如 `https://api.example.com/data`,可以通过注入的`RestTemplate`实例来完成请求。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class ExternalApiService { @Autowired private RestTemplate restTemplate; public String callExternalApi() { String url = "https://api.example.com/data"; // 发起GET请求并接收响应体为String类型 return restTemplate.getForObject(url, String.class); } } ``` 如果接口返回的是结构化数据,可以定义一个对应的POJO类来接收响应: ```java public class DataResponse { private String id; private String name; // Getters and Setters } ``` 然后修改服务方法: ```java public DataResponse callExternalApiForData() { String url = "https://api.example.com/data"; return restTemplate.getForObject(url, DataResponse.class); } ``` ### 错误处理与日志记录 调用第三方接口时,网络问题或接口变更可能导致异常。因此,建议添加适当的异常处理机制,例如使用`try-catch`捕获`RestClientException`。 ```java import org.springframework.web.client.RestClientException; public DataResponse callExternalApiWithExceptionHandling() { String url = "https://api.example.com/data"; try { return restTemplate.getForObject(url, DataResponse.class); } catch (RestClientException e) { // 记录日志并处理异常 System.err.println("调用第三方接口失败: " + e.getMessage()); return null; } } ``` ### 支持POST请求的示例 如果需要发送POST请求并传递JSON参数,可以使用`postForObject`方法: ```java public DataResponse postDataToExternalApi(DataRequest request) { String url = "https://api.example.com/submit"; return restTemplate.postForObject(url, request, DataResponse.class); } ``` 其中`DataRequest`是发送给接口的请求数据类。 ### 总结 通过上述步骤,可以在Spring Boot 3中成功使用`RestTemplate`调用第三方API[^2]。需要注意的是,虽然`RestTemplate`功能强大且简单易用,但在响应式编程和非阻塞I/O方面不如`WebClient`灵活[^1]。因此,根据项目需求选择合适的HTTP客户端是关键。 ---
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值