Basic authentication for REST API using spring restTemplate

前端 未结 8 1270
眼角桃花
眼角桃花 2020-11-29 21:02

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.

8条回答
  •  忘掉有多难
    2020-11-29 21:17

    As of Spring 5.1 you can use HttpHeaders.setBasicAuth

    Create Basic Authorization header:

    String username = "willie";
    String password = ":p@ssword";
    HttpHeaders headers = new HttpHeaders();
    headers.setBasicAuth(username, password);
    ...other headers goes here...
    

    Pass the headers to the RestTemplate:

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

    Documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

提交回复
热议问题