有一个simple Spring-Starter application,有一个(休息)控制器,如:
@GetMapping("/foo")
public String foo() {
return "bar";
}
使用java >= 11,我们可以用java.net.http客户端测试HTTP协议版本(无需额外依赖):
package com.example.test.http.version;
import java.io.IOException;
import java.net.URI;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class IntegrationTests {
@LocalServerPort
private int port;
@Test
public void testJavaDotNet() throws IOException, InterruptedException {
java.net.http.HttpClient client = java.net.http.HttpClient.newBuilder()
.build(); // or configure a (test) bean
java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port + "/foo"))
.build();
java.net.http.HttpResponse<String> response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());
assertNotNull(response);
assertEquals(java.net.http.HttpClient.Version.HTTP_1_1, response.version());
}
}
关键点:
使用 java 也可以选择,我们可以使用:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<!-- <version>4.5.13</version> managed via spring-boot-dependencies -->
<scope>test</scope>
</dependency>
..和:
@Test
public void testApache() throws IOException {
org.apache.http.client.HttpClient client = org.apache.http.impl.client.HttpClientBuilder.create()
.build();// or configure (test) bean(s)
org.apache.http.HttpResponse response = client.execute(
new org.apache.http.client.methods.HttpGet("http://localhost:" + port + "/foo")
);
org.apache.http.ProtocolVersion protocolV = response.getStatusLine().getProtocolVersion();
assertNotNull(protocolV);
assertEquals("HTTP", protocolV.getProtocol());
assertEquals(1, protocolV.getMajor());
assertEquals(1, protocolV.getMinor());
}
对不起,OkHttp!
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<!-- <version>3.14.9</version> managed via spring-boot-dependencies -->
<scope>test</scope>
</dependency>
还有,“瞧”:
@Test
public void testOkHttp() throws IOException {
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder().url(getUriString("/foo")).build();
try (okhttp3.Response response = client.newCall(request).execute()) {
assertEquals(okhttp3.Protocol.HTTP_1_1, response.protocol());
} catch (RuntimeException reexc) {
org.junit.jupiter.api.Assertions.fail(reexc);
}
}
这可能不是最后的选择...
当你设法访问ServletRequest(在你的测试中)时,你可以发出:getProtocol(),比如here。