How do we consume REST api with Http basic authentication in spring?
In this Spring Boot RestTemplate POST request in below code snippet,
we will create a POST API and then test it by sending request body along with request headers using exchange() method.
HelloRequestDTO helloRequestDTO=new helloRequestDTO();//should have data
RestTemplate restTemplate = new RestTemplate();
String URL="https://api.test.code";
StringBuilder buildURIPath = new StringBuilder(URL);
buildURIPath.append("/"+"veify");
buildURIPath.append("/"+transact);
logger.info("Request with {} " , buildURIPath);
URI uri = URI.create(buildURIPath.toString());
logger.info("Request URI: {} ",uri);
logger.info("Request Body: {} ",helloRequestDTO);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password); //Basic Auth
logger.info("U and P: {} , {}",username,password); //username, password
HttpEntity<HelloRequestDTO> httpEntityRequest = new HttpEntity<HelloRequestDTO>(helloRequestDTO,headers);
logger.info("Request entity: {} ",httpEntityRequest);
ResponseEntity<HelloResponseDTO> helloResponseDtoEntity = restTemplate.exchange(uri, HttpMethod.POST,httpEntityRequest, HelloResponseDTO.class);
HelloResponseDTO helloResponseDTO = helloResponseDtoEntity.getBody();
logger.info("helloResponseDTO Body: {} ",helloResponseDTO);
logger.info("helloResponse Entity: {} ",helloResponseDtoEntity);
if(helloResponseDtoEntity.getStatusCode().equals(HttpStatus.CREATED)) {
logger.info("Verify Response Created {} " , HttpStatus.CREATED);
saveResponse(request,status,helloResponseDtoEntity.toString());
response.setResCode("00");
response.setResMsg("Success");
}
else
{
logger.info("Verify Response Status failed {} " ,helloResponseDtoEntity.getStatusCode());
status=helloResponseDtoEntity.getStatusCode().toString();
saveResponse(request,status,helloResponseDtoEntity.toString());
}
Recent Comments