繁体   English   中英

如何在 spring 引导中发送带有 header、参数和正文的 post restful api 作为 rest 模板

[英]How to send post restful api with header, params, and body as a rest template in spring boot

我需要消耗需要 header、正文和参数的宁静 api。

有什么方法可以将参数、正文和标头与 resttemplate 一起发送吗?

您可以尝试 Webclient 将消息发布到特定的 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));

这是一个使用 RestTemplate 发送 Post 请求的简单例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM