Java测试-RestTemplate-@requestBody

在java的test代码中,如果遇到了要传入@requestBody声明的参数时,可以使用以下代码

String infra = "{\"upperId\":110000,\"areaName\":\"测试BaseArea\",\"remark\":\"备注\"}";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
HttpEntity<String> strEntity = new HttpEntity<String>(infra,headers);

RestTemplate restTemplate = new RestTemplate();
JSONObject jo2 = restTemplate.postForObject(url,strEntity,JSONObject.class);
System.out.println(jo2);

infra为json字符串

strEntity为传递用的参数


提取自:http://blog.youkuaiyun.com/qwe6112071/article/details/51042634



### 如何使用 RestTemplate 进行 POST 请求并设置 UTF-8 编码 当使用 `RestTemplate` 发送 HTTP POST 请求时,如果需要确保数据以 UTF-8 编码传输,则可以通过配置请求头中的 `Content-Type` 和 `Accept-Charset` 属性来实现。以下是具体方法: #### 配置 UTF-8 编码的示例代码 以下是一个完整的示例,展示如何通过 `RestTemplate` 设置 UTF-8 编码进行 POST 请求。 ```java import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.client.RestTemplate; public class Utf8PostExample { public static void main(String[] args) { // 创建 RestTemplate 实例 RestTemplate restTemplate = new RestTemplate(); // 定义 URL 地址 String url = "http://example.com/api"; // 构建请求体 (JSON 数据为例) String requestBody = "{\"name\":\"张三\",\"description\":\"这是一个测试描述\"}"; // 设置请求头,指定 Content-Type 为 application/json 并带有 UTF-8 字符集 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8)); // 将头部和请求体封装到 HttpEntity 中 HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers); // 执行 POST 请求 String response = restTemplate.postForObject(url, requestEntity, String.class); // 输出响应结果 System.out.println(response); } } ``` #### 关键点解析 1. **设置 Content-Type**: 使用 `MediaType.APPLICATION_JSON` 表明请求体是 JSON 格式的数据[^4]。 2. **指定字符集**: 调用 `setAcceptCharset` 方法并将 `StandardCharsets.UTF_8` 添加到列表中,从而确保服务器接收到的是 UTF-8 编码的数据[^1]。 3. **构建请求实体**: 将自定义的请求头 (`HttpHeaders`) 和请求体一起封装成 `HttpEntity` 对象[^3]。 4. **执行 POST 请求**: 利用 `postForObject` 或其他适合的方法完成请求操作[^2]。 #### 注意事项 为了防止非 ASCII 字符引发乱码问题,在实际开发中建议始终显式声明字符集为 UTF-8。此外,还需确认目标服务端能够正确处理该编码方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值