spring 如何在Sping Boot 应用中通过GET请求将请求体中的json数据发送到外部API

mzaanser  于 2023-05-16  发布在  Spring
关注(0)|答案(1)|浏览(206)

我必须将JSON数据发送到外部API,以便post方法从外部API获取数据。我想发送的JSON数据是这样的。{“key1”:“value1”,“key2”:“value2”,“key3”:“value 3”}如何在Sping Boot 应用中通过GET请求将请求体中的json数据发送给外部API

8yoxcaq7

8yoxcaq71#

如果JSON数据很大或包含特殊字符,则在URL中编码整个JSON数据可能不切实际。最好使用POST请求而不是GET请求在请求体中传输JSON数据。如果有必要,你可以这样做:

public void sendData(String jsonData) throws URISyntaxException {
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    String url = "https://yoururl.com/api?data=" + jsonData;
    RequestEntity<?> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI(url));

    ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class); // GET request
    String responseBody = responseEntity.getBody();

    // do your stuff
}

相关问题