添加基本的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();
}
如果您使用的是Spring 5.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();
}
希望这能有所帮助!
curl -u fred:fred
,无需笨重的手动标头。Spring也是如此。 - divanov