diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java index b3613755b..836c988cf 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java @@ -45,6 +45,7 @@ import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpException; +import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; import org.apache.hc.core5.http.Method; @@ -90,6 +91,17 @@ public class RequestAddCookies implements HttpRequestInterceptor { return; } + final Header cookieHeader = request.getHeader(HttpHeaders.COOKIE); + // Check if a Cookie header is already present + if (cookieHeader != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("Skipping cookie addition, Cookie header already present in the request"); + } + // Skip adding cookies if the Cookie header is already present + return; + } + + final HttpClientContext clientContext = HttpClientContext.cast(context); final String exchangeId = clientContext.getExchangeId(); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java index a100ff67b..deb096ae1 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java @@ -410,4 +410,27 @@ public class TestRequestAddCookies { Assertions.assertEquals("name1=value; name2=value; name3=value", headers1[0].getValue()); } + @Test + public void testSkipAddingCookiesWhenCookieHeaderPresent() throws Exception { + // Prepare a request with an existing Cookie header + final HttpRequest request = new BasicHttpRequest("GET", "/"); + request.addHeader("Cookie", "existingCookie=existingValue"); + + final HttpRoute route = new HttpRoute(this.target, null, false); + + final HttpClientContext context = HttpClientContext.create(); + context.setRoute(route); + context.setCookieStore(this.cookieStore); + context.setCookieSpecRegistry(this.cookieSpecRegistry); + + final HttpRequestInterceptor interceptor = RequestAddCookies.INSTANCE; + interceptor.process(request, null, context); + + // Check that no additional cookies were added + final Header[] headers = request.getHeaders("Cookie"); + Assertions.assertNotNull(headers); + Assertions.assertEquals(1, headers.length); + Assertions.assertEquals("existingCookie=existingValue", headers[0].getValue()); + } + }