以json身份发送请求体,通过HTTPEntity获取请求 [英] Sending Request body as json to GET request through httpentity
本文介绍了以json身份发送请求体,通过HTTPEntity获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以Json身份发送外部API的GET请求的请求正文示例。
下面是示例json,需要在请求正文中添加才能通过GET请求发送 至外部接口: ‘ {"nameidentify":["Name-1","Name-2","Name-3"]}
'''
'Assume i am getting values from one API like.. "Name-1","Name-2","Name-3" those values i need to
pass to other API through GET request.For example below i am hardcoding the values for reference...'
'''
String[] namesArray={"Name-1","Name-2","Name-3"}
JSONObject jsobObject=new JSONObject();
jsonObject.put("nameidentify",namesArray);
HttpHeaders headers=new HttpHeaders();
headers.add("Accept",MediaType.APPLICATION_JSON);
headers.add("Content-Type",MediaType.APPLICATION_JSON);
HttpEntity<String> otherentity=new HttpEntity<>(jsobObject.toString(),headers);
List<Map>getnameResponse=restTemplate.
exchange(externalAPIurl,HttpMethod.GET
,otherentity,ArrayList.class)
.getBody();
当我调用外部API时,收到上述代码的400个错误请求。可能是他们没有收到的身体。有谁能对此提供一些想法。提前谢谢…… ‘
推荐答案
请编写代码可能有帮助。这对我很管用,从&q;Res&q;取回你的POJO。
import org.springframework.web.client.RestTemplate;
import com.google.gson.JsonObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
RestTemplate restTemplate = new RestTemplate();
String url = "<external api url>";
JsonObject jsobObject=new JsonObject();
jsobObject.addProperty("someJsonProperty", "someJsonPropertyValue");
HttpHeaders headers=new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
headers.add("Content-Type",MediaType.APPLICATION_JSON.toString());
HttpEntity<String> httpEntity = new HttpEntity<>(jsobObject.toString(), headers);
String res = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class).getBody();
这篇关于以json身份发送请求体,通过HTTPEntity获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文