Home > OS >  How to send post restful api with header, params, and body as a rest template in spring boot
How to send post restful api with header, params, and body as a rest template in spring boot

Time:02-24

I need to consume restful api that required header, body, and params.

Are there any way to send params, body, and headers together with resttemplate?

CodePudding user response:

Thats how you can do it -> https://attacomsian.com/blog/spring-boot-resttemplate-post-request-json-headers

CodePudding user response:

You can try Webclient to post message to specific e/p, ref - https://medium.com/p/9863094bac3 for ex-

UriCimponenets uriComponents =UriComponentsBuilds.fromHttpUrl(“http://endpoint/{param}")
 .buildAndExpand(inputParam);
HttpHeaders headers= new HttpHeaders ();
Webclient webclient;
//post response status of operation .
String response=webclient.method(HttpMethod.POST)
      .uri (uriComponents.toUri())
      .headers(httpHeaders-> {
               httpHeaders.add(“key”,”value”);
                })
      .contentType(MediaType.APPLICATION_JSON)
      .body(BodyInserters.fromValue(<jsonStringBody>))
      .exchange()
      .flatMap(clientResponse -> {
           if(clientResponse.statusCode().is4xxClientError())
              {
             clientResponse->             {clientResponse.bodyToMono(String.class).subscriber(errorBody->log.error(error.Body));
    return Mono.Error(new                  ResponseStatusException(clientResponse.statusCode()));
             }
           else 
             return clientResponse.bodyToMono(String.class);                           })
      .doOnSuccess(clientResposne -> { log.info(“Response:       {}”,clientResponse)})
      .block(Duration,ofSeconds(50));

CodePudding user response:

This is a simple example of send Post request using RestTemplate:

// pretend RestTemplate already initialized

String url = "your url";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION.JSON); // whatever u want
headers.set("KEY", "VALUE");

HttpEntity requestHeader = new HttpEntity(headers);

// set url, header, and Type of value to be returned from the request
ResponseEntity<?> response = restTemplate.postForEntity(url, requestHeader, String.class); 

  • Related