下面是使用 RestTemplate 发送 POST 请求并传递 JSONObject 参数的示例代码:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class RestTemplateExample {

    public static void main(String[] args) {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put('key1', 'value1');
        requestParams.put('key2', 'value2');
        // 将请求参数转换为 JSONObject 对象
        org.json.JSONObject jsonObject = new org.json.JSONObject(requestParams);

        // 构建请求体
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonObject.toString(), headers);

        // 发送 POST 请求
        String url = 'http://example.com/api';
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        // 获取响应结果
        String response = responseEntity.getBody();
        System.out.println(response);
    }
}

注意:需要添加相关依赖,例如 spring-web 和 json 依赖。

Java8 使用 RestTemplate 发送 POST 请求并传递 JSONObject 参数

原文地址: http://www.cveoy.top/t/topic/qwSU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录