有多种方法可以将基本的HTTP身份验证添加到 RestTemplate
。
1.对于单个请求
try {
String url = "https://jsonplaceholder.typicode.com/posts";
String authStr = "username:password";
String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity request = new HttpEntity(headers);
ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);
String json = response.getBody();
} catch (Exception ex) {
ex.printStackTrace();
}
如果您使用的是Spring5.1
或更高版本,则不再需要手动设置授权标头。使用headers.setBasicAuth()
方法代替:
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");
2.对于一组请求
@Service
public class RestService {
private final RestTemplate restTemplate;
public RestService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.basicAuthentication("username", "password")
.build();
}
}
3.对于每个请求
@Bean
RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.basicAuthentication("username", "password").build();
}
希望对您有所帮助!