在分布式系统开发中,服务间通信是常见需求。作为 spring 框架的重要组件,resttemplate 为开发者提供了简洁优雅的 http 客户端解决方案。本文将从零开始讲解 resttemplate 的核心用法,并附赠真实地图 api 对接案例。
一、环境准备
在 spring boot 项目中添加依赖:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>通过配置类初始化 resttemplate:
@configuration
public class resttemplateconfig {
@bean
public resttemplate resttemplate() {
return new resttemplate();
}
}
用的时候引入
@autowired
private resttemplate resttemplate;
二、基础用法全解析
1. get 请求的三种姿势
方式一:路径参数(推荐)
string url = "https://api.example.com/users/{id}";
map<string, object> params = new hashmap<>();
params.put("id", 1001);
user user = resttemplate.getforobject(url, user.class, params);方式二:显式拼接参数
string url = "https://api.example.com/users?id=1001"; user user = resttemplate.getforobject(url, user.class);
方式三:uri 构造器
uricomponentsbuilder builder = uricomponentsbuilder
.fromuristring("https://api.example.com/users")
.queryparam("name", "john")
.queryparam("age", 25);
user user = resttemplate.getforobject(builder.touristring(), user.class);2. post 请求深度实践
发送表单数据:
multivaluemap<string, string> formdata = new linkedmultivaluemap<>();
formdata.add("username", "admin");
formdata.add("password", "123456");
responseentity<string> response = resttemplate.postforentity(
"https://api.example.com/login",
formdata,
string.class
);提交 json 对象:
user newuser = new user("alice", 28);
httpheaders headers = new httpheaders();
headers.setcontenttype(mediatype.application_json);
httpentity<user> request = new httpentity<>(newuser, headers);
user createduser = resttemplate.postforobject(
"https://api.example.com/users",
request,
user.class
);三、进阶配置技巧
1. 超时控制
@bean
public resttemplate customresttemplate() {
return new resttemplatebuilder()
.setconnecttimeout(duration.ofseconds(5))
.setreadtimeout(duration.ofseconds(10))
.build();
}
2. 拦截器实战
public class logginginterceptor implements clienthttprequestinterceptor {
@override
public clienthttpresponse intercept(httprequest request, byte[] body,
clienthttprequestexecution execution) throws ioexception {
logrequest(request, body);
clienthttpresponse response = execution.execute(request, body);
logresponse(response);
return response;
}
private void logrequest(httprequest request, byte[] body) {
// 实现请求日志记录
}
private void logresponse(clienthttpresponse response) {
// 实现响应日志记录
}
}注册拦截器:
@bean
public resttemplate resttemplate() {
resttemplate resttemplate = new resttemplate();
resttemplate.setinterceptors(collections.singletonlist(new logginginterceptor()));
return resttemplate;
}四、实战案例:腾讯地图路线规划
@service
public class mapservice {
@value("${tencent.map.key}")
private string apikey;
@autowired
private resttemplate resttemplate;
public drivingroute calculateroute(location start, location end) {
string url = "https://apis.map.qq.com/ws/direction/v1/driving/"
+ "?from={start}&to={end}&key={key}";
map<string, string> params = new hashmap<>();
params.put("start", start.tostring());
params.put("end", end.tostring());
params.put("key", apikey);
responseentity<mapresponse> response = resttemplate.getforentity(
url,
mapresponse.class,
params
);
if (response.getstatuscode() == httpstatus.ok &&
response.getbody().getstatus() == 0) {
return response.getbody().getresult().getroutes().get(0);
}
throw new mapserviceexception("路线规划失败");
}
}五、最佳实践建议
- 响应处理策略
- 使用
responseentity<t>获取完整响应信息 - 实现自定义错误处理器
responseerrorhandler - 对于复杂 json 结构,建议定义完整的 dto 类
- 使用
- 性能优化
- 启用连接池(推荐 apache httpclient)
- 合理设置超时时间
- 考虑异步调用(结合 asyncresttemplate)
- 安全防护
- 启用 https
- 敏感参数加密处理
- 配置请求频率限制
六、常见问题排查
问题1:收到 400 bad request
- 检查请求参数格式
- 确认 content-type 设置正确
- 验证请求体 json 结构
问题2:出现乱码
- 设置正确的字符编码
- 检查服务端和客户端的编码一致性
- 在 headers 中明确指定
charset=utf-8
问题3:超时配置不生效
- 确认使用的 resttemplate 实例正确
- 检查连接池配置是否覆盖超时设置
- 验证网络防火墙设置
到此这篇关于spring boot 中 resttemplate 的核心用法指南的文章就介绍到这了,更多相关spring boot resttemplate使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论