RestTemplate调用API的常用写法

摘要

本文介绍了RestTemplate调用http的几种写法,包括post+get,及传递参数的方式,让我们拿下它。

可选配置

依赖坐标pom.xml

xml 复制代码
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

<!-- 统一使用依赖注入 private final RestTemplate restTemplate; -->

自定义配置

ini 复制代码
package org.coffeebeans.resttemplate;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

/**
 * <li>ClassName: RestTemplateConfig </li>
 * <li>Author: OakWang </li>
 */
@Configuration
publicclassRestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(30000); // 连接超时时间(毫秒)
        factory.setReadTimeout(30000); // 读取超时时间(毫秒)
        RestTemplate restTemplate = new RestTemplate(factory);
        MappingJackson2HttpMessageConverterjsonConverter = new MappingJackson2HttpMessageConverter();
        restTemplate.getMessageConverters().add(jsonConverter);// 添加JSON消息转换器
        return restTemplate;
    }
}

实现get请求

  • GET+空参
ini 复制代码
String requestUrl = "https://jsonplaceholder.typicode.com/posts/1";
ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class);
if (Objects.equals(HttpStatus.OK, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}
  • GET+单参
arduino 复制代码
String requestUrl = "https://jsonplaceholder.typicode.com/posts/{id}";
ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class, 1); // 参数值为 1
if (Objects.equals(HttpStatus.OK, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}
  • GET+多参-方式1
dart 复制代码
String requestUrl = "https://jsonplaceholder.typicode.com/comments?id={id}&email={email}";
Map<String, Object> params = new HashMap<>();
params.put("id", 1);
params.put("email", "Eliseo@gardner.biz");
ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class, params);
if (Objects.equals(HttpStatus.OK, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}
  • GET+多参-方式2
arduino 复制代码
String requestUrl = UriComponentsBuilder.fromHttpUrl("https://jsonplaceholder.typicode.com/posts/1/comments")
        .queryParam("id", "3")
        .queryParam("email", "Nikita@garfield.biz")
        .toUriString();
ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class);
if (Objects.equals(HttpStatus.OK, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}

实现post请求

  • POST+空参
ini 复制代码
String requestUrl = "https://jsonplaceholder.typicode.com/posts";
ResponseEntity<Object> response = restTemplate.postForEntity(requestUrl, null, Object.class);
if (Objects.equals(HttpStatus.CREATED, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}
  • POST+JSON 实体对象参数
ini 复制代码
String requestUrl="https://jsonplaceholder.typicode.com/posts";

List<MyEntity> entityList = new ArrayList<>(); //对象参数
entityList.add(MyEntity.builder().title("foo").body("bar").userId("1").build());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "");
HttpEntity<Object> requestEntity = new HttpEntity<>(entityList, headers);

ResponseEntity<Object> response = restTemplate.postForEntity(requestUrl, requestEntity, Object.class);
if (Objects.equals(HttpStatus.CREATED, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}
  • POST+JSON 对象参数
ini 复制代码
String requestUrl="https://jsonplaceholder.typicode.com/posts";

Map<String, String> params = new HashMap<>();
params.put("title", "foo");
params.put("body", "bar");
params.put("userId", "1");
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
    form.add(entry.getKey(), entry.getValue());
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(form, headers);
ResponseEntity<Object> response = restTemplate.postForEntity(requestUrl, requestEntity, Object.class);
if (Objects.equals(HttpStatus.CREATED, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}
  • POST+表单提交
dart 复制代码
String requestUrl="https://";
// 1. 初始化参数
Map<String, String> params = new HashMap<>();
params.put("title", "foo");
// 2. 构造 MultiValueMap
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
    form.add(entry.getKey(), entry.getValue());
}
// 3. 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 4. 发送请求 返回Object或者指定类型
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(form, headers);
ResponseEntity<Object> response = restTemplate.postForEntity(requestUrl, requestEntity, Object.class);
//5.处理结果
if (Objects.equals(HttpStatus.OK, response.getStatusCode())) {
    log.info("请求响应结果: {}, {}", requestUrl, response.getBody());
    // 解析...
}

总结

以上我们整理了RestTemplate调用接口的几种用法,包括post+get,空参、单参、多参的使用场景。

关注公众号:咖啡Beans

在这里,我们专注于软件技术的交流与成长,分享开发心得与笔记,涵盖编程、AI、资讯、面试等多个领域。无论是前沿科技的探索,还是实用技巧的总结,我们都致力于为大家呈现有价值的内容。期待与你共同进步,开启技术之旅。

相关推荐
佛系打工仔7 分钟前
绘制K线第一章:可见区间处理
java
wangkay8812 分钟前
【Java 转运营】Day02:抖音直播间流量底层逻辑全解析
java·新媒体运营
Coder_Boy_20 分钟前
基于SpringAI的在线考试系统-企业级软件研发工程应用规范实现细节
大数据·开发语言·人工智能·spring boot
5***b9724 分钟前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
AIGCExplore39 分钟前
Jenkins 全局配置及工具验证教程
java·servlet·jenkins
枷锁—sha42 分钟前
彻底解决 Google Gemini 报错:异常流量与 IP 地址冲突排查指南
网络·网络协议·tcp/ip
qq_3181215944 分钟前
Java大厂面试故事:Spring Boot、微服务与AI场景深度解析
java·spring boot·redis·微服务·ai·kafka·spring security
玛丽莲茼蒿1 小时前
javaSE 集合框架(五)——java 8新品Stream类
java·开发语言
程序员小假1 小时前
设计一个支持万人同时抢购商品的秒杀系统?
java·后端
L***d6701 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端