Spring Boot 2.6.0 + Spring MVC项目如何测试接口使用的HTTP协议版本
测试Spring Boot接口HTTP协议版本的实现方案
原因说明
你使用的默认TestRestTemplate基于JDK原生HttpURLConnection实现,确实没有暴露HTTP协议版本的获取接口,需要替换底层HTTP客户端实现来拿到该信息,下面是两种可直接落地的方案:
方案1:使用Apache HttpClient5实现测试
第一步引入测试依赖:
<dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <scope>test</scope> </dependency>
第二步编写测试代码:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class IntegrationTest { @LocalServerPort private int port; private final CloseableHttpClient httpClient = HttpClients.createDefault(); @Test public void canGet() throws IOException { String url = "http://localhost:" + port + "/foo"; ClassicHttpRequest request = ClassicRequestBuilder.get(url).build(); try (CloseableHttpResponse response = httpClient.execute(request)) { assertEquals(HttpStatus.SC_OK, response.getCode()); // 直接获取协议版本做断言 assertEquals("HTTP/2", response.getVersion().toString()); // 如果要兼容原有逻辑也可以自行把响应体转成JsonResponse } } }
方案2:使用OkHttp实现测试
第一步引入测试依赖:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <scope>test</scope> <version>4.10.0</version> </dependency>
第二步编写测试代码:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class IntegrationTest { @LocalServerPort private int port; private final OkHttpClient okHttpClient = new OkHttpClient(); @Test public void canGet() throws IOException { Request request = new Request.Builder() .url("http://localhost:" + port + "/foo") .build(); try (Response response = okHttpClient.newCall(request).execute()) { assertEquals(200, response.code()); // 直接获取协议版本做断言 assertEquals(Protocol.HTTP_2, response.protocol()); String bodyStr = response.body().string(); // 自行把bodyStr反序列化为JsonResponse做后续校验即可 } } }
额外注意事项
- 请先确认服务端HTTP/2配置已正确开启:在配置文件中添加
server.http2.enabled=true,如果使用明文HTTP/2(h2c,非HTTPS场景),还需要额外配置内嵌容器支持h2c,默认内嵌Tomcat/Undertow的HTTP/2仅开启在HTTPS端口下。 - 以上示例中的HttpClient5和OkHttp默认已支持HTTP/2协商,不需要额外配置。
内容的提问来源于stack exchange,提问作者Volodya Lombrozo
相关产品推荐
相关产品推荐

