gpt4 book ai didi

java - 配置 Spring RestTemplate

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:23 25 4
gpt4 key购买 nike

使用以下代码来调用 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);

对此有以下疑问-

  1. 我可以使用工厂模式来获取 RestTemplate 而不是使用 new.RestTemplate 吗?它的优点和缺点是什么。
  2. 当前正在将凭据添加到上述代码的 header 中。是否有更好的方法来实现它(例如配置或其他适合生产代码的方法)。

谢谢

最佳答案

  1. RestTemplate 的一般使用模式是,您按照您想要的方式配置一个,然后在您的所有应用程序中重用该配置。是thread safe但创建起来可能会很昂贵,因此您应该尽可能少地创建(最好只有一个)并重用它们。

  2. 有多种方法可以配置RestTemplate以自动向所有请求添加基本身份验证,但在我看来,它太复杂了,不值得 - 您需要用 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);

尽管我建议添加更多帮助器方法来创建实体并向其添加任何其他标准 header 。

关于java - 配置 Spring RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37178652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com