使用 spring restTemplate 对 POST REST API 进行身份验证

Authentication for POST REST API with spring restTemplate

我想使用 Spring RESTTemplate 来 post 一个对象到网络服务器并取回一个对象。

这里是一段代码:

String authStringEncoded = 
                Base64.getEncoder().encodeToString
                    ("582f3e4a9e933168ea1048e6:98c6f2736c5f02279d767ce7ddfe7e5d".getBytes("utf-8"));


        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + authStringEncoded);


        HttpEntity<String> request = new HttpEntity<String>(headers);

        RestTemplate rt = new RestTemplate();
        rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        rt.getMessageConverters().add(new StringHttpMessageConverter());
        String uri = new String(REGISTERING_NEW_DEVICES.replace("{devicetype-id}", KIT_TYPE_ID));


        TdkDevice deviceC3DF86B = new TdkDevice();
        deviceC3DF86B.setId("C3DF86B");
        deviceC3DF86B.setPal("44CFFFC9D5F8E8B2F36");

        DeviceRegistration deviceRegistration = new  DeviceRegistration();
        deviceRegistration.getIds().add(deviceC3DF86B);

        rt.postForObject(uri, HttpMethod.POST, request, deviceRegistration, DeviceRegistration.class);

但是我遇到了一个编译错误:

The method postForObject(String, Object, Class<T>, Object...) in the type RestTemplate is not applicable for the arguments (String, HttpMethod, HttpEntity<String>, DeviceRegistration, 
 Class<DeviceRegistration>)

您的服务电话应该如下所示:

rt.postForObject(uri, request, DeviceRegistration.class);

根据spring RestTemplate api,postForObject 方法的参数应该如下:

参数:

  • url - URL
  • request - 要发布的对象(可能为空)
  • responseType - return 值的类型
  • uriVariables - 扩展模板的变量

API Reference