首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以json的形式发送请求体,通过httpentity获取请求

以json的形式发送请求体,通过httpentity获取请求
EN

Stack Overflow用户
提问于 2020-11-04 23:45:58
回答 1查看 60关注 0票数 0

示例请求体,作为Json通过外部API的GET请求发送。

下面是需要在请求正文中添加示例json,以便通过GET请求发送到外部API:‘

代码语言:javascript
复制
        {"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错误的请求。可能是他们没有收到的身体。有人能提前提供一些关于this.Thanks的想法吗?“”“

EN

回答 1

Stack Overflow用户

发布于 2021-10-13 18:18:44

请编写代码可能会有所帮助。这对我很有效,来自"res“让你的pojo回来。

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64683261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档