简体   繁体   English

RestAssured:如何避免在请求中发送 User-Agent header

[英]RestAssured: How to avoid sending the User-Agent header in a request

For one of my test, I want to send a request without User-Agent header. Even if I don't specify it in the request, a default one with value Apache-HttpClient/4.5.9 (Java/1.8.0_222) is added to the request.对于我的一个测试,我想发送一个没有用户代理 header 的请求。即使我没有在请求中指定它,默认值Apache-HttpClient/4.5.9 (Java/1.8.0_222)是添加到请求中。

Is there a way to disable this behavior?有没有办法禁用此行为?

This is the request I am trying to send.这是我要发送的请求。 As can be seen, the User-Agent is not set explicitly but it is still added implicitly by Apache HttpClient.可以看出,User-Agent 没有显式设置,但它仍然是由 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");

Here's a solution to set a custom User Agent with RestAssured httpClientConfig.这是使用 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;
        }
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM