Java基础、中级、高级、架构面试资料

RestTemplate 发送 Authorization Basic 认证

JAVA herman 4130浏览
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

RestTemplate 是一个非常强大的 http 请求调用工具,根据它的名字就知道,它非常的适合调用 Rest 请求的场景。

在做 OAuth2 或者第三方认证的程序员中,我们往往需要进行 Basic 基本认证。这个涉及到 HttpHeaders 设置和 Basic 加密。

如果使用的不对,可能会报:org.springframework.web.client.HttpClientErrorException: 401 null 异常。我这里提供两种 HTTP Basic Authentication 基本认证用法。

第一种,使用 BasicAuthorizationInterceptor 拦截器。

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(username, password));
restTemplate.getForObject(url, String.class);

第二种,手动设置 HttpHeaders,并对用户名和密码进行 Base64 处理。

String auth_Str = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth_Str.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
HttpHeaders headers = new HttpHeaders();
headers.set("authorization", authHeader);
restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null, headers),String.class).getBody();

注意上面的一个编码格式,US-ASCII。也可以不需要,具体看你的架构场景!

String user = "www.xttblog.com";
String password = "taoge";
String userMsg = user + ":" + password;
String base64UserMsg = Base64.getEncoder().encodeToString(userMsg.getBytes());
System.out.println("base64UserMsg:" + base64UserMsg);

String url = "http://url:port/api";
String postBody = "hello world";

HttpHeaders headers = new HttpHeaders();
headers.add("User-Agent", "www.xttblog.com");
headers.add("Authorization ", base64UserMsg);
HttpEntity<String> entity = new HttpEntity<>(postBody, headers);

ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, entity, JSONObject.class);

System.out.println(response.getBody().toJSONString());

参考资料

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » RestTemplate 发送 Authorization Basic 认证