RestAssured:如何避免在请求中发送用户代理标头



对于我的一个测试,我想发送一个没有User Agent头的请求。即使我没有在请求中指定它,也会将值为Apache-HttpClient/4.5.9 (Java/1.8.0_222)的默认值添加到请求中。

有没有办法禁用这种行为?

这是我试图发送的请求。可以看出,用户代理没有显式设置,但它仍然是由Apache HttpClient隐式添加的。

RequestSpecification request = given().
header(HttpHeaders.ACCEPT, "application/json").
header(HttpHeaders.CONTENT_TYPE, "application/json");        
if (includeAuthorizationHeader) {
request = request.header(HttpHeaders.AUTHORIZATION, bearerAuth(token));
}
Response response = request.
body(DataRequest.builder().
id("test-client").
timestamp(DATE_FORMAT.format(Date.from(Instant.now()))).
build()).
expect().
statusCode(expectedStatusCode).
contentType(expectedContentType).
when().
post(endpoint + "/api/test");

这里有一个使用RestAssured httpClientConfig设置自定义用户代理的解决方案。

HttpClientConfig httpClientConfig = RestAssured.config.getHttpClientConfig();
RestAssured.config.httpClient(httpClientConfig.httpClientFactory(() -> {
RestAssuredConfig config = RestAssured.config();
HttpClientConfig httpClientConfig = config.getHttpClientConfig();
RestAssured.config = config.httpClient(
httpClientConfig.httpClientFactory(() -> {
DefaultHttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUserAgent(client.getParams(), "User Agent A");
return client;
}
);
}

相关内容

最新更新