当前位置: 首页 > wzjs >正文

网站建设公司推荐理由河源市住房城乡和建设局网站

网站建设公司推荐理由,河源市住房城乡和建设局网站,网站开发好还是app好,口碑营销的策略RestTemplate 全面详解及示例 1. RestTemplate 简介 定义:Spring 提供的同步 HTTP 客户端,支持多种 HTTP 方法(GET/POST/PUT/DELETE 等),用于调用 RESTful API。核心特性: 支持请求头、请求体、URI 参数的…

RestTemplate 全面详解及示例


1. RestTemplate 简介
  • 定义:Spring 提供的同步 HTTP 客户端,支持多种 HTTP 方法(GET/POST/PUT/DELETE 等),用于调用 RESTful API。
  • 核心特性
    • 支持请求头、请求体、URI 参数的灵活配置。
    • 可直接返回 ResponseEntity 获取状态码和响应头。
    • 支持对象序列化(如 JSON)和反序列化。
  • 依赖(Spring Boot 项目):
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    

2. 示例代码详解

示例 1:GET 请求(带请求头,获取状态码和响应头)
// 1. 创建 RestTemplate 实例
RestTemplate restTemplate = new RestTemplate();// 2. 构建请求 URI(包含路径参数)
String uri = "http://api.example.com/users/{id}";
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("id", "123");// 3. 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer token_123");
headers.setContentType(MediaType.APPLICATION_JSON);// 4. 发送 GET 请求并获取 ResponseEntity
ResponseEntity<User> response = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<>(headers), // 请求体为空,仅传递头User.class, // 响应体反序列化类型uriVariables
);// 5. 处理响应
int statusCode = response.getStatusCodeValue(); // 获取状态码
HttpHeaders responseHeaders = response.getHeaders(); // 获取响应头
User user = response.getBody(); // 获取响应体对象

示例 2:POST 请求(传递 JSON 请求体)
// 1. 创建请求体对象(使用 Jackson 自动序列化)
User newUser = new User("John", 25);// 2. 构建请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);// 3. 创建 HttpEntity(包含头和请求体)
HttpEntity<User> request = new HttpEntity<>(newUser, headers);// 4. 发送 POST 请求
ResponseEntity<String> response = restTemplate.postForEntity("http://api.example.com/users",request,String.class // 返回的响应类型(如成功返回 "Created")
);// 5. 处理响应
String locationHeader = response.getHeaders().getFirst("Location"); // 获取 Location 头

示例 3:PUT/PATCH 请求(更新资源)
// 1. 更新对象
User updatedUser = new User("John Doe", 26);// 2. 构建请求头和请求体
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> request = new HttpEntity<>(updatedUser, headers);// 3. 发送 PUT 请求
ResponseEntity<Void> response = restTemplate.exchange("http://api.example.com/users/123",HttpMethod.PUT,request,Void.class // 无响应体时使用 Void
);// 4. 检查状态码
if (response.getStatusCode() == HttpStatus.OK) {System.out.println("Update successful");
}

示例 4:DELETE 请求
// 发送 DELETE 请求
ResponseEntity<Void> response = restTemplate.exchange("http://api.example.com/users/123",HttpMethod.DELETE,null, // 无请求体Void.class
);if (response.getStatusCode() == HttpStatus.NO_CONTENT) {System.out.println("Resource deleted");
}

示例 5:自定义响应类型(如 Map)
// 将响应体反序列化为 Map
ResponseEntity<Map<String, Object>> response = restTemplate.getForEntity("http://api.example.com/data",new ParameterizedTypeReference<Map<String, Object>>() {}
);Map<String, Object> data = response.getBody();

示例 6:使用 ResponseExtractor 定制响应
// 自定义提取器:提取响应体中的某个字段
ResponseExtractor<String> extractor = response -> {if (response.getStatusCode() == HttpStatus.OK) {return response.getHeaders().getFirst("X-Custom-Header"); // 提取自定义头}return null;
};// 使用 exchange 方法
String customHeader = restTemplate.exchange("http://api.example.com/headers",HttpMethod.GET,null,extractor // 传递自定义提取器
);

示例 7:批量操作(查询多个资源)
// 使用 UriComponentsBuilder 构建带查询参数的 URI
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://api.example.com/users").queryParam("page", 1).queryParam("size", 10);// 发送 GET 请求并获取列表
ResponseEntity<User[]> response = restTemplate.getForEntity(builder.toUriString(),User[].class
);User[] users = response.getBody();

3. 核心方法对比表格
方法HTTP 方法返回类型关键代码片段适用场景
getForObjectGET对象(如 User)restTemplate.getForObject(url, User.class);简单 GET 请求,直接返回对象
getForEntityGETResponseEntity<User>restTemplate.getForEntity(url, User.class);需获取状态码或响应头
postForObjectPOST对象(如 String)restTemplate.postForObject(url, request, String.class);POST 请求,直接返回结果
postForEntityPOSTResponseEntity<Void>restTemplate.postForEntity(url, request, Void.class);需检查状态码或 Location 头
exchange任意方法ResponseEntity<?>restTemplate.exchange(url, HttpMethod.POST, request, Class<T>);自定义 HTTP 方法和响应类型
deleteDELETEvoidrestTemplate.delete(url);简单删除操作

4. 关键配置与注意事项
  • 设置连接池(提升性能):

    RestTemplate restTemplate = new RestTemplate(new HttpClientErrorException.Factory(),new HttpComponentsClientHttpRequestFactory()
    );
    
  • 异常处理

    try {// 发送请求
    } catch (HttpClientErrorException e) {System.out.println("Client error: " + e.getStatusCode());
    } catch (HttpServerErrorException e) {System.out.println("Server error: " + e.getStatusCode());
    }
    
  • 自定义序列化器

    ObjectMapper objectMapper = new ObjectMapper();
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    restTemplate.getMessageConverters().add(converter);
    

5. 总结对比表格
需求实现方法关键代码注意事项
发送 JSON 请求体使用 HttpEntity<User>HttpEntity<String>HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);确保序列化配置正确
获取状态码和响应头返回 ResponseEntity<T>response.getStatusCode(); response.getHeaders();处理 2xx/4xx/5xx 状态码
自定义响应类型使用 ParameterizedTypeReference 或泛型new ParameterizedTypeReference<List<User>>() {}处理复杂泛型类型
响应提取器实现 ResponseExtractor 接口或使用预定义提取器restTemplate.exchange(url, HttpMethod.GET, null, extractor);简化复杂响应处理逻辑

关键总结

  1. 核心类
    • RestTemplate:核心客户端,提供所有 HTTP 方法。
    • HttpEntity:封装请求头和请求体。
    • ResponseEntity:封装响应头、状态码和响应体。
  2. 最佳实践
    • 使用 exchange 方法统一处理复杂场景。
    • 通过 ResponseEntity 获取完整响应信息。
    • 自定义 HttpMessageConverter 处理特殊序列化需求。
  3. 替代方案
    Spring Boot 3.x 已弃用 RestTemplate,推荐使用 WebClient(响应式、非阻塞)。

通过以上示例和配置,开发者可以灵活实现 REST API 的全场景调用需求。


文章转载自:

http://HFEfIBfR.dLmqn.cn
http://FjJfSz1U.dLmqn.cn
http://Y61qpyTg.dLmqn.cn
http://MQiyVdqR.dLmqn.cn
http://fa3Y5rDR.dLmqn.cn
http://W93MCv15.dLmqn.cn
http://uUhnpPWf.dLmqn.cn
http://c5vvflFu.dLmqn.cn
http://1ZACQmzG.dLmqn.cn
http://pCdba9zI.dLmqn.cn
http://Xf0T61J0.dLmqn.cn
http://vyqMncm2.dLmqn.cn
http://H3XqS3Xx.dLmqn.cn
http://Pp5STEc4.dLmqn.cn
http://ogAs61G2.dLmqn.cn
http://U2N1NrTC.dLmqn.cn
http://TYGUqx8X.dLmqn.cn
http://71tLdbs7.dLmqn.cn
http://IHqsuqLh.dLmqn.cn
http://pwXRjjs2.dLmqn.cn
http://TtRmvERQ.dLmqn.cn
http://pUxRZbij.dLmqn.cn
http://gg1GkpMk.dLmqn.cn
http://BxCKrCX2.dLmqn.cn
http://K2HmqAtA.dLmqn.cn
http://D5kuZ1qe.dLmqn.cn
http://YXMZ7IaA.dLmqn.cn
http://a24FF7xT.dLmqn.cn
http://n64d92X4.dLmqn.cn
http://67bjUdua.dLmqn.cn
http://www.dtcms.com/wzjs/700917.html

相关文章:

  • 郑州网站建设注意事项山东华邦建设网站首页
  • c 如何做网站池州网站建设怎么样
  • 会做网站开发 但是不会二次开发手机上怎么上传网站吗
  • 做网站菠菜什么意思湖南在建工程查询
  • 江苏军民融合网站建设做网站的项目介绍
  • 网站建设博客一些免费的网站
  • 网站排名降级的原因有哪些网站的权限管理怎么做
  • 网站页脚的信息都有什么如何做简易网站
  • 重庆网站排名公司wordpress增加js效果
  • 做网站空间不给账号密码wordpress网站网页加密
  • 网站搭建北京深圳市南山区做网站的小公司
  • 企业网站建设中存在的问题分析网站如何推广营销
  • 网站 asp.net php想自己在家做外贸网站
  • 数据库在网站建设中的作用网站怎么做背景
  • 荷兰网站域名做招聘网站
  • 织梦dedeeims网站打不开网站建设的费用是多少
  • 淄博网站制作定制广告传媒公司起名大全最新
  • 织梦网站转移服务器四川在线城市论坛
  • 杭州建站价格网站开发维护员挣钱吗
  • 厂房出租做推广什么网站好如何在百度上搜索到自己的网站
  • 做网站公司职务深圳注册公司需要多少钱
  • 太原建网站的公司商标logo设计生成器免费
  • 温州建设银行官方网站手机搞笑网站模板下载安装
  • 台州cms建站系统游戏ui设计是做什么的
  • 电脑端网站和手机网站区别湖北联诺建设网站
  • 专门建站的公司简洁手机购物网站会员中心模板
  • 做网站需要什么图片wordpress用户前台删除文章
  • 购物网站建设计划书 中国人免费的片
  • 网站开发团队人员构成在线下载免费软件的网站
  • 如何建设自己企业网站装修网站线怎样做