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-
- Can I use factory pattern for getting RestTemplate instead of using new. What will be the advantages and disadvantages of it.
- 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