如何使用RestTemplate.exchange调用指定表单提交风格的服务?
使用RestTemplate.exchange调用目标POST接口示例
下面是针对你提供的服务接口,使用RestTemplate.exchange发起调用的完整实现及关键说明:
完整代码示例
import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; 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; // 确保ServiceObligationResponse是与接口返回结构匹配的实体类 public class ServiceCallExample { public static void main(String[] args) { // 初始化RestTemplate(Spring环境中推荐用@Autowired注入) RestTemplate restTemplate = new RestTemplate(); // 1. 配置请求头 HttpHeaders headers = new HttpHeaders(); // 指定表单编码类型,匹配接口的consumes配置 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 填入三个必填请求头的实际值 headers.set("KEY", "your-actual-key"); headers.set("ID", "your-actual-id"); headers.set("AUTH_HEADER", "your-actual-auth-token"); // 2. 构造表单请求参数(对应接口的@RequestParam Map) MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); // 根据接口需求添加参数,示例添加两个参数 formParams.add("paramName1", "paramValue1"); formParams.add("paramName2", "paramValue2"); // 3. 组装请求实体(参数+请求头) HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formParams, headers); // 4. 发起请求 String serviceUrl = "http://your-service-domain/service"; // 替换为实际服务地址 ResponseEntity<ServiceObligationResponse> response = restTemplate.exchange( serviceUrl, HttpMethod.POST, requestEntity, ServiceObligationResponse.class ); // 处理响应结果 if (response.getStatusCode().is2xxSuccessful()) { ServiceObligationResponse responseBody = response.getBody(); // 这里编写你的业务逻辑处理代码 } else { // 处理非成功响应,比如401未授权等 if (response.getStatusCodeValue() == 401) { // 对应接口抛出的CustomUnAuthorizedException,可做针对性处理 } } } }
关键细节说明
- 请求头配置:必须设置
ContentType为application/x-www-form-urlencoded,同时严格添加接口要求的三个必填自定义请求头,值需替换为实际业务中的有效内容。 - 表单参数构造:接口用
@RequestParam Map接收参数,因此必须使用MultiValueMap(Spring提供的表单参数容器),不能用普通HashMap,否则RestTemplate无法正确解析为表单格式。 - RestTemplate初始化:在Spring Boot项目中,建议通过
RestTemplateBuilder构建实例,可以统一配置超时、拦截器等,示例中的直接new方式仅适合简单测试场景。 - 异常处理:当接口抛出
CustomUnAuthorizedException时,RestTemplate会转换为HttpClientErrorException.Unauthorized异常,可通过捕获该异常处理未授权场景。
内容的提问来源于stack exchange,提问作者S.R.D
相关产品推荐
相关产品推荐

