调用第三方接口,使用RestTemplate发送http请求

本文讲述了在工作中遇到调用接口时如何构建请求头,将token加入Authorization,使用Gson将传参对象转换为JSON格式,并通过RestTemplate发送POST请求的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于在工作上遇见了调用接口的需求,在进行代码编写时对于传参有一点小问题,然后对其解决之后,写一篇文章,在以后能够用到。

1.首先

//构建请求头,将token添加到Authorization字段中
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.set("Authorization", token);
headers.setContentType(MediaType.APPLICATION_JSON);

// 构建RestTemplate
RestTemplate restTemplate = new RestTemplate();

//构建请求体
HttpEntity<String> objectHttpEntity = new HttpEntity<>(json,headers);

在构建请求体时需要注意将对象转换成JSON格式,不然在发送请求时会报错。

根据自己传参格式将传参的dto转换为JSON

// 创建一个GsonBuilder对象
GsonBuilder gsonBuilder = new GsonBuilder();
// 自定义日期时间的序列化格式
gsonBuilder.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (localDateTime, type, jsonSerializationContext) ->
jsonSerializationContext.serialize(localDateTime.format(DateTimeFormatter.ISO_DATE_TIME)));
// 将employeeGetByTimeWindowDTO转换成JSON格式
Gson gson = gsonBuilder.create();
String json = gson.toJson(employeeGetByTimeWindowDTO);

发送请求:

ResponseEntity<EmployeeGetByTimeWindowResponse> responseEntity = restTemplate.postForEntity(
requestUrl,
objectHttpEntity,
EmployeeGetByTimeWindowResponse.class
);

这样,一个调用第三方接口的功能就基本实现。希望能够在实现该需求时能够有所帮助!

### 使用 Java RestTemplate 调用第三方 API 接口 为了调用第三方提供的 API 接口,在 Spring Boot 应用程序中可以利用 `RestTemplate` 实现 HTTP 请求发送。下面展示了一个具体的例子,即通过 `RestTemplate` 来获取天气预报数据。 #### 创建配置类保存 API Key 首先定义一个用于存储 API 密钥的属性类: ```java @Data public class WeatherProp extends BaseBean { /** * 调用接口key */ private String key; } ``` 此部分代码创建了名为 `WeatherProp` 的 POJO 类来封装 weather API 所需的关键信息[^1]。 #### 初始化 RestTemplate 并执行 GET 请求 接下来编写服务层逻辑,初始化 `RestTemplate` 对象并构建 URL 发送 GET 请求给目标服务器: ```java @Service public class WeatherService { @Autowired private RestTemplate restTemplate; @Value("${weather.api.url}") private String apiUrl; @Autowired private WeatherProp weatherProp; public JSONObject getWeatherForecast(String cityCode) throws JSONException { // 构建完整的URL地址 StringBuilder urlBuilder = new StringBuilder(apiUrl); urlBuilder.append("?city=").append(cityCode).append("&key=").append(weatherProp.getKey()); ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlBuilder.toString(), String.class); if (responseEntity.getStatusCode() == HttpStatus.OK){ return new JSONObject(responseEntity.getBody()); }else{ throw new RuntimeException("Failed to fetch data from external service"); } } } ``` 上述代码片段展示了如何使用 `RestTemplate#getForEntity()` 方法发起带有查询参数的城市编码和密钥的 GET 请求,并接收 JSON 格式的响应体作为字符串解析成 `JSONObject` 返回[^3]。 注意:这里假设已经在 application.properties 文件中设置了 `weather.api.url=https://api.weather.com/v1/location/{city}/forecast/daily/7day.json?language=zh-CN&units=m`. #### 配置 RestTemplate Bean 最后一步是在应用程序上下文中注册 `RestTemplate` bean: ```java @Configuration public class AppConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } } ``` 这样就可以让 Spring 自动注入已经配置好的 `RestTemplate` 到任何需要的地方[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值