API的基本身份验证

API的基本身份验证

本文介绍了使用spring restTemplate进行REST API的基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在RestTemplate中是全新的,基本上也在REST API中。我想通过Jira REST API在我的应用程序中检索一些数据,但是回到401 Unauthorized。找到并发表关于的文章,但不是真的知道如何将其重写为java,因为该示例使用curl命令行方式。我很感激任何建议或建议如何重写:

I am completely new in RestTemplate and basically in the REST APIs also. I want to retrieve some data in my application via Jira REST API, but getting back 401 Unauthorised. Found and article on jira rest api documentation but don't really know how to rewrite this into java as the example uses the command line way with curl. I would appreciate any suggestion or advice how to rewrite:

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31"

使用spring rest模板进入java。其中ZnJlZDpmcmVk是base64编码的用户名:密码字符串。非常感谢。

into java using spring rest template. Where the ZnJlZDpmcmVk is a base64 encoded string of username:password. Thank you very much.

推荐答案

取自,我认为通过填写标题值,这将是最自然的方式并将标题传递给模板。

Taken from the example on this site, I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template.

这是填写标题授权

String plainCreds = "willie:p@ssword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

这是将标题传递给REST模板:

And this is to pass the header to the REST template:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

这篇关于使用spring restTemplate进行REST API的基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:36