1

Have the following code for getting calling the REST service

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

Have the following doubts for this-

  1. Can I use factory pattern for getting RestTemplate instead of using new. What will be the advantages and disadvantages of it.
  2. Currently adding the credentials into headers in the above code. Is there some better way to achieve it(example in configuration or some other way that can be suitable for production code).

Thanks

Raniz
  • 10,882
  • 1
  • 32
  • 64
Rehan
  • 929
  • 1
  • 12
  • 29
  • Did you just copy that code from somewhere and now you don't know how to use it? Maybe you should read the documentation. – Kayaman May 12 '16 at 06:25
  • Used it in my code and it works good. got it from some place. Going through the documentation...But still had these doubts – Rehan May 12 '16 at 06:30
  • Well, after you've gone through the documentation all your doubts should be cleared. – Kayaman May 12 '16 at 06:41
  • Ok. Thanks Kayaman :). Still if any experienced person wants to share his knowledge of how he or she did this, would be thankful. – Rehan May 12 '16 at 06:49

1 Answers1

0
  1. The general usage pattern of RestTemplate is that you configure one in the way you want it and then reuse that througouht all your application. It is thread safe but can be expensive to create so creating as few as possible (ideally just one) and reusing them is what you should do.

  2. There are ways of configuring the RestTemplate to automatically add basic authentication to all requests but IMO it's too complex to be worth it - you need to mess around a bit with Http Components and create your own request factory so I think the easiest solution is to just break out the manual step into a helper class.

--

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

Your code now turns into:

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

Though I'd suggest adding a few more helper methods to create an entity and add any other standard headers to it.

Community
  • 1
  • 1
Raniz
  • 10,882
  • 1
  • 32
  • 64
  • Thanks Raniz the changes you suggested were helpful. – Rehan May 12 '16 at 07:11
  • @Raniz I am also using `RestTemplate` in one of my projects but I am not able to figure out how to `set a request configuration per request` using `RestTemplate`. I have opened SO question [here](http://stackoverflow.com/questions/37125694/initialize-socket-timeout-value-in-httpclient-and-then-use-it-with-resttemplate/). Wanted to see if you can help out. Any help will be greatly appreciated. – user1950349 May 12 '16 at 18:21