本文介绍了如何在RestTemplate中将主体作为Json发送以从API获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从Rest调用者获取数据以从API获取数据,当我使用curl时,我的api端点支持带有json主体的get方法作为请求,它正在起作用,我的curl命令是:
Hi I am trying to get data from the Rest caller to get data from the API my api end point support the get method with the json body as a request when I use curl it is working my curl command is :
curl -X GET http://ec2-URL.com:5000/TL/data -H 'Content-Type: application/json' -d '{ "meta": "NJ", "name": "US"}'
我的Spring代码是这样的:
And My Spring code is this:
public String getData() {
RestTemplate restTemplate = new RestTemplate();
try {
String requestJson = "{ \"meta\": \"NJ\", \"name\": \"US\" }";
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
ResponseEntity<?> lado = restTemplate.exchange("http://ec2-URL.com:5000/TL/data", HttpMethod.GET, entity, Object.class);
} catch (Exception exc) {
logger.error("[WebServiceCallerUtil] Exception while calling . {} ", exc.getMessage());
}
return " ";
}
每次遇到错误时,我都会提出错误的要求.我知道这很容易,但是..我也尝试像这样使用Map:
I am getting bad request everytime am I dong any wrong.. I know its very easy but..I tried to use Map also like this :
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("meta", "NJ");
map.add("name", US);
HttpEntity<?> entity = new HttpEntity<>(map, httpHeaders);
我的错误是什么?如何在get方法中发送json正文?
推荐答案
尝试一下,
private static HttpEntity<?> getHeaders(){
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
return new HttpEntity<>(headers);
}
public String getData() {
RestTemplate restTemplate = new RestTemplate();
try {
String requestJson = "{ \"meta\": \"NJ\", \"name\": \"US\" }";
Object lado = restTemplate.getForObject("http://ec2-URL.com:5000/TL/data?requestJson= {requestJson}", Object.class,requestJson, getHeaders());
} catch (Exception exc) {
logger.error("[WebServiceCallerUtil] Exception while calling . {} ", exc.getMessage());
}
return " ";
}
-
这篇关于如何在RestTemplate中将主体作为Json发送以从API获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!