RestTemplate客户端调用服务接口

本文介绍了如何在Spring Boot项目中使用RestTemplate进行接口测试,并展示了如何通过`sendPostRequest`发送POST请求并处理响应。同时,探讨了如何通过RestTemplateBuilder构建可配置的RestTemplate实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过new RestTemplate()测试接口

package com.ml.app.pms.gh;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class WebServiceTest {
    String ghRequestUrl = "http://XXX/find";

    @Test
    public void web_service_test() {
        String sendJson = "{\"op\":\"findSalary\", \"yearMonth\":\"202201\"}";
        String resultStr = sendPostRequest(ghRequestUrl, sendJson);
        System.out.println("返回:" + resultStr);
    }

    private String sendPostRequest(String url, String params) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth("ceshi", "ceshi123");
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交 application/json
        headers.setContentType(MediaType.APPLICATION_JSON);

        //将请求头部和参数合成一个请求
        HttpEntity<String> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求,将返回的结构使用ResultVO类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);

        return response.getBody();
    }
}

采用RestTemplateBuilder构建RestTemplate(实际应用)

@Slf4j
@Component
@ConditionalOnProperty({
    "xxx.url",
})
public class HttpXxxInterfaceClient implements IHttpXxxInterfaceClient {
    private final RestTemplate restTemplate;
    private final String serverHost;

    public HttpBbguInterfaceClient(RestTemplateBuilder builder, @Value("${xxx.url}") String serverHost) {
        this.restTemplate = builder
            .setConnectTimeout(Duration.ofMinutes(5))
            .setReadTimeout(Duration.ofMinutes(5))
            .build();

        this.serverHost = serverHost;
    }
}


// 调用接口并返回
private <T> List<T> doRequest(Object request, Class<T> responseClass) {
        log.trace("Begin URL->{}, requestBody is {}", this.serverHost, request.toString());
        try {
            String resp = this.restTemplate.postForObject(this.serverHost, request, String.class);
            InterfaceResult apiResult = JSON.parseObject(resp, InterfaceResult.class);

            if (Objects.isNull(apiResult)) {
                throw BusinessException.withArgs(ErrorCode.ERR_10500, "返回异常,返回信息为空");
            }

            return JSONObject.parseArray(apiResult.getDATA(), responseClass);
        } catch (BusinessException ex) { // 自己抛出来的ex
            throw ex;
        } catch (Exception ex) {
            log.error("bbgu invoke error[class={}, msg={}]", ex.getClass(), ex.getLocalizedMessage());
            String errorMessage = String.format("bbgu invoke error[class=%s, msg=%s]", ex.getClass(), ex.getLocalizedMessage());
            throw BusinessException.withArgs(ErrorCode.ERR_10500, errorMessage);
        }
    }

### 使用 Spring `RestTemplate` 调用 WebService 接口 为了通过 `RestTemplate` 发起 HTTP 请求来调用 WebService 接口,通常需要配置并实例化 `RestTemplate` 对象。下面是一个简单的例子展示如何创建 `RestTemplate` 并设置客户端请求工厂: ```java import org.springframework.context.annotation.Bean; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } ``` 当涉及到 SOAP 或 RESTful 风格的 Web Service 时,可能还需要构建特定的数据结构作为请求体发送给服务器端。对于基于 XML 的消息交换模式(如SOAP),可以定义相应的 Java 类映射到预期的消息格式,并利用 JAX-B 注解帮助序列化/反序列化过程。 这里给出一个具体的案例,假设有一个名为 `DownloadFileByMaterialCodeRequest` 的请求对象用于下载文件操作[^3]: ```java // 导入必要的包... @Data // Lombok annotation to generate getters/setters automatically. @XmlRootElement(name = "DownloadFileByMaterialCode", namespace = "http://example.com/") @XmlAccessorType(XmlAccessType.FIELD) public class DownloadFileByMaterialCodeRequest { @XmlElement(name = "MaterialCode", namespace = "http://example.com/") private String materialCode; @XmlElement(name = "FileType", namespace = "http://example.com/") private String fileType; @XmlElement(name = "Category", namespace = "http://example.com/") private String category; } ``` 有了上述准备之后,在实际发起请求前还需指定目标 URL 和其他必要参数。接着就可以使用 `postForObject()` 方法执行 POST 请求并将响应结果转换为目标类型: ```java String url = "https://service.example.com/download"; DownloadFileByMaterialCodeRequest request = new DownloadFileByMaterialCodeRequest(); request.setMaterialCode("ABC123"); request.setFileType("PDF"); request.setCategory("Documents"); ResponseEntity<byte[]> response = restTemplate.postForEntity(url, request, byte[].class); if (response.getStatusCode().is2xxSuccessful()) { byte[] fileContent = Objects.requireNonNull(response.getBody()); // 处理返回的内容... } else { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusCodeValue()); } ``` 这段代码展示了如何使用 `RestTemplate` 向远程 WebService 提交带有自定义实体类型的请求,并处理其二进制形式的回复数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值