0

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

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

        {"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 Bad Request。可能是他们没有收到的身体。任何人都可以对此提供一些想法。在此先感谢...'''

4

1 回答 1

0

请编码可能会有所帮助。这对我有用,从“res”让你的 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();
于 2021-10-13T18:18:44.087 回答