java - 配置 Spring RestTemplate

标签 java rest resttemplate spring-rest

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

相关文章:

java - 无法导入 SpringApplicationContextLoader

java - 自动提交开关的并发症

javascript - Nodejs GET REST API 和频繁访问 MongoDb 数据库

rest - 从 WSDL/XML 以编程方式生成 Swagger YAML Open API 规范

java - RestTemplate ClientHttpResponse.getBody() 抛出 I/O 错误

java - H2数据库列大小

java - 在 Web 应用程序中显示来自本地计算机的 JFree 图表图像

Azure 机器学习 REST API : why is the prediction included in the Sample Request?

android - Rest API - 如何添加自定义 header ?

java - 使 RestTemplate 处理响应正文,无论状态如何