x This domain is for sale. If you intrested, Please contact : webspeckle@gmail.com

How to send HTTP request in spring boot?

If you need to call remote REST services from your application, you can use Spring Framework’s RestTemplate class. Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances.

RestTemplateBuilder includes a number of useful methods that can be used to quickly configure a RestTemplate. For example, to add BASIC auth support you can use builder.basicAuthorization("user", "password").build().


Eg:
HttpResponse httpResponse;
HttpRequest httpRequest = new HttpRequest();
HttpRequest.setName("webspeckle.com");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<HttpRequest> entity = new HttpEntity<>(httpRequest,headers);

RestTemplate restTemplate = new RestTemplate();

try
{
    ResponseEntity<HttpResponse> responseEntity = restTemplate.exchange("REST_URL", HttpMethod.POST, entity, HttpResponse.class);
    httpResponse = responseEntity.getBody();
    //Success
}
catch(HttpStatusCodeException ex)
{
    //Error in REST request
}

No comments:

Post a Comment