Java 使用SpringRESTTemplate对RESTAPI进行基本身份验证

Java 使用SpringRESTTemplate对RESTAPI进行基本身份验证,java,spring,resttemplate,jira-rest-api,Java,Spring,Resttemplate,Jira Rest Api,我对RestTemplate和RESTAPI都是全新的。我想通过Jira REST API检索应用程序中的一些数据,但未经授权就返回401。找到并继续文章,但不知道如何将其重写为java,因为示例使用了curl的命令行方式。如有任何关于如何重写的建议或建议,我将不胜感激: curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/r

我对RestTemplate和RESTAPI都是全新的。我想通过Jira REST API检索应用程序中的一些数据,但未经授权就返回401。找到并继续文章,但不知道如何将其重写为java,因为示例使用了curl的命令行方式。如有任何关于如何重写的建议或建议,我将不胜感激:

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31"
使用SpringREST模板转换为java。其中ZnJlZDpmcmVk是username:password的base64编码字符串。非常感谢。

摘自,我认为这将是最自然的方法,通过填写页眉值并将页眉传递给模板

这是为了填写标题
授权

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模板:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();
HttpEntity请求=新的HttpEntity(头);
ResponseEntity response=restemplate.exchange(url、HttpMethod.GET、请求、Account.class);
Account=response.getBody();

参考Spring Boot的
TestRestTemplate
实现,如下所示:

private void addAuthentication(String username, String password) {
    if (username == null) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
            interceptors));
}
TestRestTemplate restTemplate = new TestRestTemplate();

具体请参见addAuthentication()方法,如下所示:

private void addAuthentication(String username, String password) {
    if (username == null) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
            interceptors));
}
TestRestTemplate restTemplate = new TestRestTemplate();
private void addAuthentication(字符串用户名、字符串密码){
如果(用户名==null){
返回;
}
列表拦截器=集合
.singletonList(新基本授权拦截器)(
用户名、密码);
setRequestFactory(新的侦听ClientHttPrequestFactory(getRequestFactory()),
拦截器);
}
同样,您可以轻松地创建自己的
RestTemplate

通过继承,如
testrestemplate
,如下所示:

private void addAuthentication(String username, String password) {
    if (username == null) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
            interceptors));
}
TestRestTemplate restTemplate = new TestRestTemplate();

而不是按如下方式实例化:

private void addAuthentication(String username, String password) {
    if (username == null) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
            interceptors));
}
TestRestTemplate restTemplate = new TestRestTemplate();
就这样做吧:

TestRestTemplate restTemplate = new TestRestTemplate(user, password);
它对我有用,我希望它能帮助我

您可以使用弹簧靴

(在SB 2.1.0之前,它是
#基本授权

(可能)不导入弹簧靴的最简单方法

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

从Spring 5.1开始,您可以使用
HttpHeaders.setBasicAuth

创建基本授权标头:

String username = "willie";
String password = ":p@ssword";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
...other headers goes here...
将标题传递给RestTemplate:

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

ResponseEntity

有多种方法可以将基本HTTP身份验证添加到
RestTemplate

1.一个请求
试试看{
//请求url
字符串url=”https://jsonplaceholder.typicode.com/posts";
//创建身份验证凭据
字符串authStr=“用户名:密码”;
字符串base64Creds=Base64.getEncoder().encodeToString(authStr.getBytes());
//创建标题
HttpHeaders=新的HttpHeaders();
标题。添加(“授权”、“基本”+base64Creds);
//创建请求
HttpEntity请求=新的HttpEntity(标头);
//提出请求
ResponseEntity response=new restemplate().exchange(url,HttpMethod.GET,request,String.class);
//获取JSON响应
字符串json=response.getBody();
}捕获(例外情况除外){
例如printStackTrace();
}
如果您使用的是Spring
5.1
或更高版本,则不再需要手动设置授权标头。改用
headers.setBasicAuth()
方法:

//创建标题
HttpHeaders=新的HttpHeaders();
headers.setBasicAuth(“用户名”、“密码”);
2.对于一组请求
@服务
公共类服务{
私有最终RestTemplate RestTemplate;
公共RestService(RestTemplateBuilder RestTemplateBuilder){
this.restTemplate=restTemplateBuilder
.basicAuthentication(“用户名”、“密码”)
.build();
}
//在此处使用'restemplate'实例
}
3.每一个请求
@Bean
RestOperations restTemplateBuilder(restTemplateBuilder restTemplateBuilder){
返回restTemplateBuilder.basicAuthentication(“用户名”、“密码”).build();
}

我希望有帮助

使用
setBasicAuth
定义凭据

HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("myUsername", myPassword);
然后按照您喜欢的方式创建请求

例如:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, 
request, String.class);
String body = response.getBody();
HttpEntity请求=新的HttpEntity(头);
ResponseEntity response=restemplate.exchange(url,HttpMethod.GET,
请求,String.class);
String body=response.getBody();

另请参见curl支持开箱即用的身份验证,您只需告诉它username和passoword
curl-u fred:fred
,不需要笨重的手动标题。春天也是一样。谢谢——这对我很有效。我必须指出,如果您不想使用org.apache.commons.codec.binary.Base64类,而是想使用android Base64类:import android.util.Base64;,您可以将上面的一行替换为:byte[]base64CredsBytes=Base64.encode(plainCredsBytes,Base64.DEFAULT)@嗨,这对我执行GET请求很有效。虽然它在发布时没有给出403。你能帮我吗?java 8你可以使用Base64.getMimeEncoder().encodeToString()TestRestTemplate在将spring boot升级到1.3后似乎不起作用。xIsn这不应该用于单元测试而不是发布代码吗?你救了我一天。非常感谢,谢谢!这是最快最简单的方法。这是最快的方法。不需要额外的依赖项。@自2.1.0以来已弃用,支持#基本身份验证(字符串用户名、字符串密码)。这不是一个好的解决方案,因为它会为通过
restemplate
发送的每个请求添加一个授权头。请注意,使用拦截器会导致流不再工作。原因如下:
exchange()
->
doExecute()
,->
createRequest()
,->
拦截HttpAccessor.getRequestFactory()
(因为
RestTemplate
扩展了
拦截HttpAccessor
)。如果存在拦截器,
getRequestFactory()
返回一个
InterceptingClientHttpRequestFactory
,它创建
InterceptingClientHttpRequest