[英]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.