Nuñito Calzada
Nuñito Calzada

Reputation: 2086

Authentication for POST REST API with spring restTemplate

I want to use Spring RESTTemplate to post an Object to a web server and get one back.

Here the piece of code:

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);

But I got a compilation error:

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>)

Upvotes: 0

Views: 386

Answers (1)

Monzurul Shimul
Monzurul Shimul

Reputation: 8396

Your service call should be like following:

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

According to spring RestTemplate api, postForObject method's parameters should be following:

Parameters:

  • url - the URL
  • request - the Object to be POSTed (may be null)
  • responseType - the type of the return value
  • uriVariables - the variables to expand the template

API Reference

Upvotes: 1

Related Questions