已验证curl请求有效,如何用Spring RestTemplate.exchange发送整数列表?
使用Spring RestTemplate.exchange发送整数列表的方法
没问题,针对你要发送整数列表[23,24]的需求,用RestTemplate.exchange的核心操作很清晰,关键是把列表正确封装并匹配curl里的请求头配置:
先准备好要发送的整数列表:
List<Integer> ids = Arrays.asList(23, 24);构建和curl一致的请求头:
HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth("XYZ"); // 替换为你的实际Bearer Token将列表和请求头封装成
HttpEntity(这是RestTemplate发送请求的载体):HttpEntity<List<Integer>> requestEntity = new HttpEntity<>(ids, headers);最后调用
exchange方法发送POST请求:restTemplate.exchange( "https://serverurl/api/list/GetByIds", HttpMethod.POST, requestEntity, YourResponseType.class // 替换为你实际期望的响应类型,比如具体的DTO类或ResponseEntity.class );
这样就完全对应你测试通过的curl命令了,请求体是JSON数组格式,请求头也和curl保持一致,能正确触发接口返回预期结果。
内容的提问来源于stack exchange,提问作者aquitted-mind
相关产品推荐
相关产品推荐

