获取以下用于调用REST服务的代码
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
String plainCreds = "test:test2";
byte[] plainCredsBytes = plainCreds.getBytes();
String base64Creds = DatatypeConverter.printBase64Binary(plainCredsBytes);
headers.add("Authorization", "Basic " + base64Creds);
headers.add("Content-type","application/x-www-form-urlencoded;charset=utf-8");
headers.set("Accept", MediaType.APPLICATION_XML_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
.queryParam("id", "id1234");
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.GET, entity, String.class);
对此有以下疑问 -
由于
答案 0 :(得分:0)
RestTemplate 的一般使用模式是您按照自己的方式配置 one ,然后通过所有应用程序重用它。它是thread safe,但创建起来可能很昂贵,因此尽可能少地创建(理想情况下只有一个)并重新使用它们就是你应该做的。
有一些方法可以配置 RestTemplate 以自动为所有请求添加基本身份验证,但IMO太复杂而不值得 - 你需要搞砸一下Http Components和create your own request factory所以我认为最简单的解决方案是将手动步骤分解为帮助类。
-
public class RestTemplateUtils {
public static final RestTemplate template;
static {
// Init the RestTemplate here
template = new RestTemplate();
}
/**
* Add basic authentication to some {@link HttpHeaders}.
* @param headers The headers to add authentication to
* @param username The username
* @param password The password
*/
public static HttpHeaders addBasicAuth(HttpHeaders headers, String username, String password) {
String plainCreds = username + ":" + password;
byte[] plainCredsBytes = plainCreds.getBytes();
String base64Creds = DatatypeConverter.printBase64Binary(plainCredsBytes);
headers.add("Authorization", "Basic " + base64Creds);
return headers;
}
}
您的代码现在变为:
HttpHeaders headers = RestTemplateUtils.addBasicAuth(new HttpHeaders(),
"test", "test");
headers.add("Content-type","application/x-www-form-urlencoded;charset=utf-8");
headers.set("Accept", MediaType.APPLICATION_XML_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
.queryParam("id", "id1234");
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = RestTemplateUtils.template.exchange(
builder.build().encode().toUri(),
HttpMethod.GET, entity, String.class);
虽然我建议添加一些辅助方法来创建实体并添加任何其他标准标头。