Updated examples and unit tests to make use of lambda expressions for response message processing

This commit is contained in:
Oleg Kalnichevski 2021-11-12 22:16:43 +01:00
parent 3dd37952bc
commit 0e8adf79dc
35 changed files with 564 additions and 571 deletions

View File

@ -27,7 +27,6 @@
package org.apache.hc.client5.testing.sync;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
@ -42,10 +41,11 @@ public class TestBasicConnectionManager extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet get = new HttpGet("/random/1024");
try (CloseableHttpResponse response = this.httpclient.execute(target, get)) {
this.httpclient.execute(target, get, response -> {
Assert.assertEquals(200, response.getCode());
EntityUtils.consume(response.getEntity());
}
return null;
});
}
@Test

View File

@ -53,7 +53,6 @@ import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
import org.apache.hc.client5.http.impl.auth.BasicScheme;
import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.testing.BasicTestAuthenticator;
import org.apache.hc.client5.testing.auth.Authenticator;
@ -108,12 +107,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
context.setCredentialsProvider(credsProvider);
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -130,12 +130,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
context.setCredentialsProvider(credsProvider);
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -152,12 +153,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpHost target = start();
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -182,11 +184,12 @@ public class TestClientAuthentication extends LocalServerTestBase {
.thenReturn(new UsernamePasswordCredentials("test", "test".toCharArray()));
context.setCredentialsProvider(credsProvider);
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpput, context)) {
this.httpclient.execute(target, httpput, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
}
return null;
});
}
@Test
@ -208,12 +211,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
.thenReturn(new UsernamePasswordCredentials("test", "boom".toCharArray()));
context.setCredentialsProvider(credsProvider);
try (final CloseableHttpResponse response = this.httpclient.execute(target, httpput, context)) {
this.httpclient.execute(target, httpput, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(401, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
}
@Test
@ -230,12 +234,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
.thenReturn(new UsernamePasswordCredentials("test", "test".toCharArray()));
context.setCredentialsProvider(credsProvider);
try (final ClassicHttpResponse response = this.httpclient.execute(target, httppost, context)) {
this.httpclient.execute(target, httppost, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -259,12 +264,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
.thenReturn(new UsernamePasswordCredentials("test", "test".toCharArray()));
context.setCredentialsProvider(credsProvider);
try (final CloseableHttpResponse response = this.httpclient.execute(target, httppost, context)) {
this.httpclient.execute(target, httppost, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(401, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
}
@Test
@ -285,12 +291,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
for (int i = 0; i < 5; i++) {
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
}
return null;
});
}
Mockito.verify(authStrategy).select(Mockito.any(), Mockito.any(), Mockito.any());
@ -322,12 +329,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
for (final String requestPath: new String[] {"/blah/a", "/blah/b?huh", "/blah/c", "/bl%61h/%61"}) {
final HttpGet httpget = new HttpGet(requestPath);
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
}
return null;
});
}
// There should be only single auth strategy call for all successful message exchanges
@ -343,12 +351,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
for (final String requestPath: new String[] {"/blah/a", "/yada/a", "/blah/blah/", "/buh/a"}) {
final HttpGet httpget = new HttpGet(requestPath);
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
}
return null;
});
}
// There should be an auth strategy call for all successful message exchanges
@ -402,30 +411,33 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget1 = new HttpGet("/this");
try (final ClassicHttpResponse response1 = this.httpclient.execute(target, httpget1, context)) {
final HttpEntity entity1 = response1.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response1.getCode());
this.httpclient.execute(target, httpget1, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
}
return null;
});
final HttpGet httpget2 = new HttpGet("/this");
try (final ClassicHttpResponse response2 = this.httpclient.execute(target, httpget2, context)) {
final HttpEntity entity2 = response2.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
this.httpclient.execute(target, httpget2, context, response -> {
final HttpEntity entity2 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity2);
EntityUtils.consume(entity2);
}
return null;
});
final HttpGet httpget3 = new HttpGet("/that");
try (final ClassicHttpResponse response3 = this.httpclient.execute(target, httpget3, context)) {
final HttpEntity entity3 = response3.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response3.getCode());
this.httpclient.execute(target, httpget3, context, response -> {
final HttpEntity entity3 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity3);
EntityUtils.consume(entity3);
}
return null;
});
Mockito.verify(authStrategy, Mockito.times(2)).select(Mockito.any(), Mockito.any(), Mockito.any());
}
@ -437,7 +449,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("http://test:test@" + target.toHostString() + "/");
final HttpClientContext context = HttpClientContext.create();
Assert.assertThrows(ClientProtocolException.class, () -> this.httpclient.execute(target, httpget, context));
Assert.assertThrows(ClientProtocolException.class, () -> this.httpclient.execute(target, httpget, context, response -> null));
}
@Test
@ -454,12 +466,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
context.setAuthCache(authCache);
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response1 = this.httpclient.execute(target, httpget, context)) {
final HttpEntity entity1 = response1.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response1.getCode());
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
}
return null;
});
Mockito.verify(authenticator).authenticate(Mockito.any(), Mockito.any(), Mockito.any());
}
@ -479,12 +492,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
.build());
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response1 = this.httpclient.execute(target, httpget, context)) {
final HttpEntity entity1 = response1.getEntity();
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getCode());
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
}
return null;
});
Mockito.verify(authenticator).authenticate(Mockito.any(), Mockito.any(), Mockito.any());
}
@ -519,11 +533,12 @@ public class TestClientAuthentication extends LocalServerTestBase {
context.setCredentialsProvider(credsProvider);
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, response.getCode());
EntityUtils.consume(entity);
}
return null;
});
}
@Test
@ -550,10 +565,11 @@ public class TestClientAuthentication extends LocalServerTestBase {
for (int i = 0; i < 2; i++) {
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
}
return null;
});
}
}
@ -623,12 +639,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
for (int i = 0; i < 10; i++) {
final HttpGet httpget = new HttpGet("/");
httpget.setConfig(config);
try (final CloseableHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
}
}
@ -654,12 +671,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
context.setCredentialsProvider(credsProvider);
final HttpGet httpget = new HttpGet("/");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
EntityUtils.consume(entity);
}
return null;
});
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}

View File

@ -82,10 +82,11 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
final HttpContext context = HttpClientContext.create();
final HttpGet httpget = new HttpGet("/");
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED,
response.getCode());
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
static class NtlmType2MessageResponseHandler implements HttpRequestHandler {
@ -129,10 +130,11 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
final HttpContext context = HttpClientContext.create();
final HttpGet httpget = new HttpGet("/");
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED,
response.getCode());
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
@Test
@ -153,10 +155,11 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
final HttpContext context = HttpClientContext.create();
final HttpGet httpget = new HttpGet("/");
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED,
response.getCode());
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
static class NtlmType2MessageOnlyResponseHandler implements HttpRequestHandler {
@ -192,10 +195,11 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
.build());
final HttpGet httpget = new HttpGet("/");
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED,
response.getCode());
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
@Test
@ -212,10 +216,11 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
.build());
final HttpGet httpget = new HttpGet("/");
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED,
response.getCode());
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
}

View File

@ -158,16 +158,17 @@ public class TestClientRequestExecution extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/");
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
EntityUtils.consume(response.getEntity());
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
final HttpRequest reqWrapper = context.getRequest();
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
final Header[] myheaders = reqWrapper.getHeaders("my-header");
Assert.assertNotNull(myheaders);
Assert.assertEquals(1, myheaders.length);
final Header[] myheaders = reqWrapper.getHeaders("my-header");
Assert.assertNotNull(myheaders);
Assert.assertEquals(1, myheaders.length);
return null;
});
}
@Test
@ -218,7 +219,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ),
-1, null));
Assert.assertThrows(IOException.class, () ->
this.httpclient.execute(target, httppost, context));
this.httpclient.execute(target, httppost, context, response -> null));
}
@Test
@ -229,10 +230,11 @@ public class TestClientRequestExecution extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
final ClassicHttpRequest request = new BasicClassicHttpRequest("GET", "{{|boom|}}");
final ClassicHttpResponse response = this.httpclient.execute(target, request, context);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
this.httpclient.execute(target, request, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
@ -248,9 +250,11 @@ public class TestClientRequestExecution extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/stuff#blahblah");
final HttpClientContext context = HttpClientContext.create();
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest request = context.getRequest();
Assert.assertEquals("/stuff", request.getRequestUri());
@ -273,9 +277,10 @@ public class TestClientRequestExecution extends LocalServerTestBase {
final HttpGet httpget = new HttpGet(uri);
final HttpClientContext context = HttpClientContext.create();
final ClassicHttpResponse response = this.httpclient.execute(httpget, context);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
this.httpclient.execute(httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
return null;
});
final HttpRequest request = context.getRequest();
Assert.assertEquals("/stuff", request.getRequestUri());
@ -298,16 +303,14 @@ public class TestClientRequestExecution extends LocalServerTestBase {
for (int i = 0; i < 20; i++) {
final HttpGet httpget = new HttpGet("/random/1000");
executorService.schedule(new Runnable() {
executorService.schedule(httpget::cancel, 1, TimeUnit.MILLISECONDS);
@Override
public void run() {
httpget.cancel();
}
}, 1, TimeUnit.MILLISECONDS);
try {
this.httpclient.execute(target, httpget, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget)) {
EntityUtils.consume(response.getEntity());
} catch (final Exception ignore) {
}
}
@ -316,16 +319,13 @@ public class TestClientRequestExecution extends LocalServerTestBase {
for (int i = 0; i < 20; i++) {
final HttpGet httpget = new HttpGet("/random/1000");
executorService.schedule(new Runnable() {
executorService.schedule(httpget::cancel, rnd.nextInt(200), TimeUnit.MILLISECONDS);
@Override
public void run() {
httpget.cancel();
}
}, rnd.nextInt(200), TimeUnit.MILLISECONDS);
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget)) {
EntityUtils.consume(response.getEntity());
try {
this.httpclient.execute(target, httpget, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
} catch (final Exception ignore) {
}
@ -333,9 +333,10 @@ public class TestClientRequestExecution extends LocalServerTestBase {
for (int i = 0; i < 5; i++) {
final HttpGet httpget = new HttpGet("/random/1000");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget)) {
this.httpclient.execute(target, httpget, response -> {
EntityUtils.consume(response.getEntity());
}
return null;
});
}
} finally {

View File

@ -32,7 +32,6 @@ import java.net.URI;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HeaderElements;
@ -168,28 +167,36 @@ public class TestConnectionReuse extends LocalServerTestBase {
.build();
final HttpHost target = start(httpproc, null);
ClassicHttpResponse response = this.httpclient.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
this.httpclient.execute(target, new HttpGet("/random/2000"), response -> {
EntityUtils.consume(response.getEntity());
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
response = this.httpclient.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
this.httpclient.execute(target, new HttpGet("/random/2000"), response -> {
EntityUtils.consume(response.getEntity());
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
// Now sleep for 1.1 seconds and let the timeout do its work
Thread.sleep(1100);
response = this.httpclient.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
this.httpclient.execute(target, new HttpGet("/random/2000"), response -> {
EntityUtils.consume(response.getEntity());
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
// Do another request just under the 1 second limit & make
// sure we reuse that connection.
Thread.sleep(500);
response = this.httpclient.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
this.httpclient.execute(target, new HttpGet("/random/2000"), response -> {
EntityUtils.consume(response.getEntity());
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
}
@ -223,14 +230,14 @@ public class TestConnectionReuse extends LocalServerTestBase {
try {
for (int i = 0; i < this.repetitions; i++) {
final HttpGet httpget = new HttpGet(this.requestURI);
final ClassicHttpResponse response = this.httpclient.execute(
this.target,
httpget);
if (this.forceClose) {
httpget.cancel();
} else {
EntityUtils.consume(response.getEntity());
}
this.httpclient.execute(this.target, httpget, response -> {
if (this.forceClose) {
response.close();
} else {
EntityUtils.consume(response.getEntity());
}
return null;
});
}
} catch (final Exception ex) {
this.exception = ex;

View File

@ -92,9 +92,11 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
final ClassicHttpResponse response = this.httpclient.execute(target, request);
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode());
Assert.assertNull(response.getEntity());
this.httpclient.execute(target, request, response -> {
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode());
Assert.assertNull(response.getEntity());
return null;
});
}
/**
@ -112,9 +114,11 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
final ClassicHttpResponse response = this.httpclient.execute(target, request);
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
this.httpclient.execute(target, request, response -> {
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
return null;
});
}
/**
@ -132,9 +136,11 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
final ClassicHttpResponse response = this.httpclient.execute(target, request);
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
this.httpclient.execute(target, request, response -> {
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
return null;
});
}
/**
@ -151,9 +157,11 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
final ClassicHttpResponse response = this.httpclient.execute(target, request);
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
this.httpclient.execute(target, request, response -> {
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
return null;
});
}
/**
@ -217,12 +225,13 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
final ClassicHttpResponse response = this.httpclient.execute(target, request);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
this.httpclient.execute(target, request, response -> {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
Assert.assertEquals(entityText, out.toString("utf-8"));
return null;
});
response.getEntity().writeTo(out);
Assert.assertEquals(entityText, out.toString("utf-8"));
}
@Test
@ -234,12 +243,12 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
final ClassicHttpResponse response = this.httpclient.execute(target, request);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
Assert.assertEquals(entityText, out.toString("utf-8"));
this.httpclient.execute(target, request, response -> {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
Assert.assertEquals(entityText, out.toString("utf-8"));
return out;
});
}
@Test
@ -428,8 +437,8 @@ public class TestContentCodings extends LocalServerTestBase {
try {
startGate.await();
try {
final ClassicHttpResponse response = client.execute(target, request);
text = EntityUtils.toString(response.getEntity());
text = httpclient.execute(target, request, response ->
EntityUtils.toString(response.getEntity()));
} catch (final Exception e) {
failed = true;
} finally {

View File

@ -33,7 +33,6 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpStatus;
@ -96,12 +95,12 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
context.setCookieStore(cookieStore);
// First request : retrieve a domain cookie from remote server.
URI uri = new URI("http://app.mydomain.fr");
HttpGet httpRequest = new HttpGet(uri);
httpRequest.addHeader("X-Request", "1");
try (CloseableHttpResponse response1 = this.httpclient.execute(target, httpRequest, context)) {
EntityUtils.consume(response1.getEntity());
}
final HttpGet request1 = new HttpGet(new URI("http://app.mydomain.fr"));
request1.addHeader("X-Request", "1");
this.httpclient.execute(target, request1, context, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
// We should have one cookie set on domain.
final List<Cookie> cookies = cookieStore.getCookies();
@ -110,20 +109,20 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
Assert.assertEquals("name1", cookies.get(0).getName());
// Second request : send the cookie back.
uri = new URI("http://app.mydomain.fr");
httpRequest = new HttpGet(uri);
httpRequest.addHeader("X-Request", "2");
try (CloseableHttpResponse response2 = this.httpclient.execute(target, httpRequest, context)) {
EntityUtils.consume(response2.getEntity());
}
final HttpGet request2 = new HttpGet(new URI("http://app.mydomain.fr"));
request2.addHeader("X-Request", "2");
this.httpclient.execute(target, request2, context, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
// Third request : Host header
uri = new URI("http://app.mydomain.fr");
httpRequest = new HttpGet(uri);
httpRequest.addHeader("X-Request", "3");
try (CloseableHttpResponse response3 = this.httpclient.execute(target, httpRequest, context)) {
EntityUtils.consume(response3.getEntity());
}
final HttpGet request3 = new HttpGet(new URI("http://app.mydomain.fr"));
request3.addHeader("X-Request", "3");
this.httpclient.execute(target, request3, context, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
}
}

View File

@ -33,7 +33,6 @@ import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.IdleConnectionEvictor;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.TimeValue;
@ -95,14 +94,19 @@ public class TestIdleConnectionEviction extends LocalServerTestBase {
try {
for (int i = 0; i < this.count; i++) {
final HttpGet httpget = new HttpGet(this.requestUri);
try (final ClassicHttpResponse response = this.httpclient.execute(this.target, httpget)) {
this.httpclient.execute(this.target, httpget, response -> {
final int status = response.getCode();
if (status != 200) {
throw new ClientProtocolException("Unexpected status code: " + status);
}
EntityUtils.consume(response.getEntity());
Thread.sleep(10);
}
try {
Thread.sleep(10);
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
}
return null;
});
}
} catch (final Exception ex) {
this.ex = ex;

View File

@ -31,7 +31,6 @@ import java.net.Socket;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpException;
@ -98,15 +97,17 @@ public class TestMalformedServerResponse {
final HttpHost target = new HttpHost("localhost", server.getLocalPort());
try (final CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
final HttpGet get1 = new HttpGet("/nostuff");
try (final CloseableHttpResponse response1 = httpclient.execute(target, get1)) {
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response1.getCode());
EntityUtils.consume(response1.getEntity());
}
httpclient.execute(target, get1, response -> {
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpGet get2 = new HttpGet("/stuff");
try (final CloseableHttpResponse response2 = httpclient.execute(target, get2)) {
Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
EntityUtils.consume(response2.getEntity());
}
httpclient.execute(target, get2, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
}
}
}

View File

@ -32,7 +32,6 @@ import java.util.Locale;
import java.util.Set;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.ClassicHttpRequest;
@ -80,10 +79,11 @@ public class TestMinimalClientRequestExecution extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
for (int i = 0; i < 10; i++) {
final HttpGet request = new HttpGet("/");
try (final CloseableHttpResponse response = this.httpclient.execute(target, request, context)) {
this.httpclient.execute(target, request, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertNotNull(reqWrapper);
@ -108,10 +108,11 @@ public class TestMinimalClientRequestExecution extends LocalServerTestBase {
for (int i = 0; i < 10; i++) {
final HttpGet request = new HttpGet("/");
try (final CloseableHttpResponse response = this.httpclient.execute(target, request)) {
this.httpclient.execute(target, request, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
}
return null;
});
}
}

View File

@ -48,7 +48,6 @@ import org.apache.hc.client5.testing.classic.RedirectingDecorator;
import org.apache.hc.client5.testing.redirect.Redirect;
import org.apache.hc.core5.function.Decorator;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
@ -80,19 +79,18 @@ public class TestRedirects extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
final HttpGet httpget = new HttpGet("/oldlocation/100");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
}
@Test
@ -104,19 +102,19 @@ public class TestRedirects extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
final HttpGet httpget = new HttpGet("/oldlocation/100");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
}
@Test
@ -129,22 +127,22 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(1, redirects.size());
final URI redirect = new URIBuilder().setHttpHost(target).setPath("/random/100").build();
Assert.assertTrue(redirects.contains(redirect));
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(1, redirects.size());
final URI redirect = new URIBuilder().setHttpHost(target).setPath("/random/100").build();
Assert.assertTrue(redirects.contains(redirect));
}
@Test
@ -157,15 +155,16 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/50");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/50").build(),
reqWrapper.getUri());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/50").build(),
reqWrapper.getUri());
}
@Test
@ -184,14 +183,15 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
this.httpclient.execute(target, httpget, context, response -> {
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode());
Assert.assertEquals("/oldlocation/100", reqWrapper.getRequestUri());
EntityUtils.consume(response.getEntity());
}
return null;
});
}
@Test
@ -204,15 +204,15 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/123");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
reqWrapper.getUri());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
reqWrapper.getUri());
}
@Test
@ -228,19 +228,19 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/stuff");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
}
@Test
@ -256,19 +256,19 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/stuff");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
}
@Test
@ -281,15 +281,15 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/123");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
reqWrapper.getUri());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
reqWrapper.getUri());
}
@Test
@ -307,7 +307,7 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/circular-oldlocation/123");
httpget.setConfig(config);
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget));
this.httpclient.execute(target, httpget, response -> null));
Assert.assertTrue(exception.getCause() instanceof RedirectException);
}
@ -325,7 +325,7 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/circular-oldlocation/123");
httpget.setConfig(config);
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget));
this.httpclient.execute(target, httpget, response -> null));
Assert.assertTrue(exception.getCause() instanceof CircularRedirectException);
}
@ -340,17 +340,16 @@ public class TestRedirects extends LocalServerTestBase {
final HttpPost httppost = new HttpPost("/oldlocation/stuff");
httppost.setEntity(new StringEntity("stuff"));
try (final ClassicHttpResponse response = this.httpclient.execute(target, httppost, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httppost, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/echo/stuff").build(),
reqWrapper.getUri());
Assert.assertEquals("GET", reqWrapper.getMethod());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/echo/stuff").build(),
reqWrapper.getUri());
Assert.assertEquals("GET", reqWrapper.getMethod());
}
@Test
@ -369,15 +368,15 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/stuff");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
}
@Test
@ -397,16 +396,15 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/random/oldlocation");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
}
@Test
@ -425,7 +423,7 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation");
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget));
this.httpclient.execute(target, httpget, response -> null));
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(HttpException.class));
}
@ -445,7 +443,7 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation");
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget));
this.httpclient.execute(target, httpget, response -> null));
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
}
@ -467,18 +465,18 @@ public class TestRedirects extends LocalServerTestBase {
context.setCookieStore(cookieStore);
final HttpGet httpget = new HttpGet("/oldlocation/100");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final Header[] headers = reqWrapper.getHeaders("Cookie");
Assert.assertEquals("There can only be one (cookie)", 1, headers.length);
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final Header[] headers = reqWrapper.getHeaders("Cookie");
Assert.assertEquals("There can only be one (cookie)", 1, headers.length);
}
@Test
@ -493,18 +491,18 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final Header header = reqWrapper.getFirstHeader(HttpHeaders.USER_AGENT);
Assert.assertEquals("my-test-client", header.getValue());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final Header header = reqWrapper.getFirstHeader(HttpHeaders.USER_AGENT);
Assert.assertEquals("my-test-client", header.getValue());
}
@Test
@ -538,15 +536,15 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
try (final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context)) {
final HttpRequest reqWrapper = context.getRequest();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
EntityUtils.consume(response.getEntity());
}
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
MatcherAssert.assertThat(values.poll(), CoreMatchers.equalTo("gzip, x-gzip, deflate"));
MatcherAssert.assertThat(values.poll(), CoreMatchers.equalTo("gzip, x-gzip, deflate"));

View File

@ -168,10 +168,11 @@ public class TestSPNegoScheme extends LocalServerTestBase {
final String s = "/path";
final HttpGet httpget = new HttpGet(s);
final ClassicHttpResponse response = this.httpclient.execute(target, httpget);
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
this.httpclient.execute(target, httpget, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
/**
@ -199,10 +200,12 @@ public class TestSPNegoScheme extends LocalServerTestBase {
final String s = "/path";
final HttpGet httpget = new HttpGet(s);
final ClassicHttpResponse response = this.httpclient.execute(target, httpget);
EntityUtils.consume(response.getEntity());
this.httpclient.execute(target, httpget, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
}
}

View File

@ -161,16 +161,15 @@ public class TestStatefulConnManagement extends LocalServerTestBase {
this.context.setAttribute("user", this.uid);
for (int r = 0; r < this.requestCount; r++) {
final HttpGet httpget = new HttpGet("/");
final ClassicHttpResponse response = this.httpclient.execute(
this.target,
httpget,
this.context);
this.httpclient.execute(this.target, httpget, this.context, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
this.count++;
final EndpointDetails endpointDetails = this.context.getEndpointDetails();
final String connuid = Integer.toHexString(System.identityHashCode(endpointDetails));
this.context.setAttribute("r" + r, connuid);
EntityUtils.consume(response.getEntity());
}
} catch (final Exception ex) {
@ -202,9 +201,10 @@ public class TestStatefulConnManagement extends LocalServerTestBase {
// Bottom of the pool : a *keep alive* connection to Route 1.
final HttpContext context1 = new BasicHttpContext();
context1.setAttribute("user", "stuff");
final ClassicHttpResponse response1 = this.httpclient.execute(
target, new HttpGet("/"), context1);
EntityUtils.consume(response1.getEntity());
this.httpclient.execute(target, new HttpGet("/"), context1, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
// The ConnPoolByRoute now has 1 free connection, out of 2 max
// The ConnPoolByRoute has one RouteSpcfcPool, that has one free connection
@ -215,9 +215,10 @@ public class TestStatefulConnManagement extends LocalServerTestBase {
// Send a very simple HTTP get (it MUST be simple, no auth, no proxy, no 302, no 401, ...)
// Send it to another route. Must be a keepalive.
final HttpContext context2 = new BasicHttpContext();
final ClassicHttpResponse response2 = this.httpclient.execute(
new HttpHost("127.0.0.1", this.server.getPort()), new HttpGet("/"), context2);
EntityUtils.consume(response2.getEntity());
this.httpclient.execute(new HttpHost("127.0.0.1", this.server.getPort()), new HttpGet("/"), context2, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
// ConnPoolByRoute now has 2 free connexions, out of its 2 max.
// The [localhost][stuff] RouteSpcfcPool is the same as earlier
// And there is a [127.0.0.1][null] pool with 1 free connection
@ -230,13 +231,14 @@ public class TestStatefulConnManagement extends LocalServerTestBase {
// The killed conn is the oldest, which means the first HTTPGet ([localhost][stuff]).
// When this happens, the RouteSpecificPool becomes empty.
final HttpContext context3 = new BasicHttpContext();
final ClassicHttpResponse response3 = this.httpclient.execute(
target, new HttpGet("/"), context3);
this.httpclient.execute(target, new HttpGet("/"), context3, response -> {
EntityUtils.consume(response.getEntity());
return null;
});
// If the ConnPoolByRoute did not behave coherently with the RouteSpecificPool
// this may fail. Ex : if the ConnPool discared the route pool because it was empty,
// but still used it to build the request3 connection.
EntityUtils.consume(response3.getEntity());
}

View File

@ -30,7 +30,6 @@ import org.apache.hc.client5.http.auth.AuthSchemeFactory;
import org.apache.hc.client5.http.auth.StandardAuthScheme;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.win.WinHttpClients;
import org.apache.hc.client5.http.impl.win.WindowsNegotiateSchemeGetTokenFail;
@ -71,9 +70,10 @@ public class TestWindowsNegotiateScheme extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet httpGet = new HttpGet("/");
try (final CloseableHttpResponse response = customClient.execute(target, httpGet)) {
customClient.execute(target, httpGet, response -> {
EntityUtils.consume(response.getEntity());
}
return null;
});
}
}

View File

@ -27,10 +27,15 @@
package org.apache.hc.client5.http.examples;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* This example demonstrates how to abort an HTTP method before its normal completion.
@ -41,14 +46,17 @@ public class ClientAbortMethod {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
// Cancel the request after once second
executorService.schedule(httpget::cancel, 1, TimeUnit.SECONDS);
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
// Do not feel like reading the response body
// Call cancel on the request object
httpget.cancel();
}
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}

View File

@ -29,10 +29,10 @@ package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* A simple example that uses HttpClient to execute an HTTP request against
@ -49,11 +49,12 @@ public class ClientAuthentication {
final HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}
}

View File

@ -31,11 +31,11 @@ import java.io.FileInputStream;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.message.StatusLine;
/**
* Example how to use unbuffered chunk-encoded POST request.
@ -63,11 +63,12 @@ public class ClientChunkEncodedPost {
httppost.setEntity(reqEntity);
System.out.println("Executing request " + httppost.getMethod() + " " + httppost.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
httpclient.execute(httppost, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(httppost + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}

View File

@ -50,7 +50,6 @@ import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
@ -81,6 +80,7 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicLineParser;
import org.apache.hc.core5.http.message.LineParser;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;
@ -238,29 +238,24 @@ public class ClientConfiguration {
context.setCredentialsProvider(credentialsProvider);
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget, context)) {
httpclient.execute(httpget, context, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
// Once the request has been executed the local context can
// be used to examine updated state and various objects affected
// by the request execution.
// Last executed request
context.getRequest();
// Execution route
context.getHttpRoute();
// Auth exchanges
context.getAuthExchanges();
// Cookie origin
context.getCookieOrigin();
// Cookie spec used
context.getCookieSpec();
// User security token
context.getUserToken();
}
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
// Last executed request
context.getRequest();
// Execution route
context.getHttpRoute();
// Auth exchanges
context.getAuthExchanges();
// Cookie origin
context.getCookieOrigin();
// Cookie spec used
context.getCookieSpec();
// User security token
context.getUserToken();
}
}

View File

@ -29,7 +29,6 @@ package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
@ -92,10 +91,12 @@ public class ClientConnectionConfig {
.setPath("/headers")
.build();
System.out.println("Executing request " + request);
try (CloseableHttpResponse response = httpclient.execute(request)) {
httpclient.execute(request, response -> {
System.out.println("----------------------------------------");
System.out.println(request + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
}
return null;
});
}
}
}

View File

@ -34,10 +34,10 @@ import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* This example demonstrates the use of a local HTTP context populated with
@ -59,15 +59,16 @@ public class ClientCustomContext {
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
// Pass local context as a parameter
try (final CloseableHttpResponse response = httpclient.execute(httpget, localContext)) {
httpclient.execute(httpget, localContext, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(httpget + "->" + new StatusLine(response));
final List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
EntityUtils.consume(response.getEntity());
}
return null;
});
}
}

View File

@ -29,10 +29,9 @@ package org.apache.hc.client5.http.examples;
import java.net.URL;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.cookie.CookieSpecFactory;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.cookie.RFC6265CookieSpecFactory;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
@ -44,6 +43,7 @@ import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.config.Lookup;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.ssl.SSLContexts;
/**
@ -81,11 +81,12 @@ public class ClientCustomPublicSuffixList {
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}

View File

@ -34,7 +34,6 @@ import javax.net.ssl.SSLSession;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
@ -42,6 +41,7 @@ import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.Timeout;
@ -80,17 +80,17 @@ public class ClientCustomSSL {
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
final HttpClientContext clientContext = HttpClientContext.create();
try (CloseableHttpResponse response = httpclient.execute(httpget, clientContext)) {
httpclient.execute(httpget, clientContext, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
final SSLSession sslSession = clientContext.getSSLSession();
if (sslSession != null) {
System.out.println("SSL protocol " + sslSession.getProtocol());
System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
}
}
return null;
});
}
}

View File

@ -28,10 +28,10 @@ package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.pool.PoolStats;
import org.apache.hc.core5.util.TimeValue;
@ -61,11 +61,12 @@ public class ClientEvictExpiredConnections {
System.out.println("Executing request " + request.getMethod() + " " + request.getRequestUri());
try (final CloseableHttpResponse response = httpclient.execute(request)) {
httpclient.execute(request, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(request + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
}
return null;
});
}
final PoolStats stats1 = cm.getTotalStats();

View File

@ -30,10 +30,10 @@ package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* How to send a request via proxy.
@ -57,11 +57,12 @@ public class ClientExecuteProxy {
System.out.println("Executing request " + request.getMethod() + " " + request.getUri() +
" via " + proxy);
try (final CloseableHttpResponse response = httpclient.execute(target, request)) {
httpclient.execute(request, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(request + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}

View File

@ -34,15 +34,16 @@ import java.net.Socket;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.util.TimeValue;
@ -57,24 +58,27 @@ public class ClientExecuteSOCKS {
final Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new MyConnectionSocketFactory())
.build();
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
final InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
final PoolingHttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultSocketConfig(SocketConfig.custom()
.setSocksProxyAddress(socksaddr)
.build())
.build();
try (final CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build()) {
final InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
final HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);
final HttpHost target = new HttpHost("http", "httpbin.org", 80);
final HttpGet request = new HttpGet("/get");
System.out.println("Executing request " + request.getMethod() + " " + request.getUri() +
" via SOCKS proxy " + socksaddr);
try (final CloseableHttpResponse response = httpclient.execute(target, request, context)) {
httpclient.execute(target, request, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(request + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}

View File

@ -33,10 +33,8 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
@ -52,11 +50,10 @@ public class ClientFormLogin {
.setDefaultCookieStore(cookieStore)
.build()) {
final HttpGet httpget = new HttpGet("https://someportal/");
try (final CloseableHttpResponse response1 = httpclient.execute(httpget)) {
final HttpEntity entity = response1.getEntity();
System.out.println("Login form get: " + response1.getCode() + " " + response1.getReasonPhrase());
EntityUtils.consume(entity);
httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println("Login form get: " + response.getCode() + " " + response.getReasonPhrase());
EntityUtils.consume(response.getEntity());
System.out.println("Initial set of cookies:");
final List<Cookie> cookies = cookieStore.getCookies();
@ -67,18 +64,18 @@ public class ClientFormLogin {
System.out.println("- " + cookies.get(i));
}
}
}
return null;
});
final ClassicHttpRequest login = ClassicRequestBuilder.post()
.setUri(new URI("https://someportal/"))
.addParameter("IDToken1", "username")
.addParameter("IDToken2", "password")
.build();
try (final CloseableHttpResponse response2 = httpclient.execute(login)) {
final HttpEntity entity = response2.getEntity();
System.out.println("Login form get: " + response2.getCode() + " " + response2.getReasonPhrase());
EntityUtils.consume(entity);
httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println("Login form get: " + response.getCode() + " " + response.getReasonPhrase());
EntityUtils.consume(response.getEntity());
System.out.println("Post logon cookies:");
final List<Cookie> cookies = cookieStore.getCookies();
@ -89,7 +86,8 @@ public class ClientFormLogin {
System.out.println("- " + cookies.get(i));
}
}
}
return null;
});
}
}
}

View File

@ -33,7 +33,6 @@ import java.util.concurrent.atomic.AtomicLong;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.ChainElement;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
@ -46,6 +45,7 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.http.protocol.HttpContext;
/**
@ -92,11 +92,12 @@ public class ClientInterceptors {
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}
}

View File

@ -28,7 +28,6 @@ package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpEntity;
@ -103,7 +102,7 @@ public class ClientMultiThreadedExecution {
public void run() {
try {
System.out.println(id + " - about to get something from " + httpget.getUri());
try (CloseableHttpResponse response = httpClient.execute(httpget, context)) {
this.httpClient.execute(httpget, response -> {
System.out.println(id + " - get executed");
// get the response body as an array of bytes
final HttpEntity entity = response.getEntity();
@ -111,7 +110,8 @@ public class ClientMultiThreadedExecution {
final byte[] bytes = EntityUtils.toByteArray(entity);
System.out.println(id + " - " + bytes.length + " bytes read");
}
}
return null;
});
} catch (final Exception e) {
System.out.println(id + " - error: " + e);
}

View File

@ -33,11 +33,11 @@ import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* Example how to use multipart/form encoded POST request.
@ -65,15 +65,16 @@ public class ClientMultipartFormPost {
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost);
try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
httpclient.execute(httppost, response -> {
System.out.println("----------------------------------------");
System.out.println(response);
System.out.println(httppost + "->" + new StatusLine(response));
final HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
}
EntityUtils.consume(response.getEntity());
return null;
});
}
}

View File

@ -30,11 +30,11 @@ import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.auth.BasicScheme;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* An example of how HttpClient can be customized to authenticate
@ -63,11 +63,12 @@ public class ClientPreemptiveBasicAuthentication {
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) {
try (final CloseableHttpResponse response = httpclient.execute(httpget, localContext)) {
httpclient.execute(httpget, localContext, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}
}

View File

@ -33,11 +33,11 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.auth.DigestScheme;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* An example of how HttpClient can authenticate multiple requests
@ -61,9 +61,9 @@ public class ClientPreemptiveDigestAuthentication {
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) {
try (final CloseableHttpResponse response = httpclient.execute(target, httpget, localContext)) {
httpclient.execute(httpget, localContext, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
final AuthExchange authExchange = localContext.getAuthExchange(target);
@ -75,7 +75,8 @@ public class ClientPreemptiveDigestAuthentication {
"; count: " + digestScheme.getNounceCount());
}
}
}
return null;
});
}
}
}

View File

@ -32,10 +32,10 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* A simple example that uses HttpClient to execute an HTTP request
@ -63,11 +63,12 @@ public class ClientProxyAuthentication {
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri() +
" via " + proxy);
try (final CloseableHttpResponse response = httpclient.execute(target, httpget)) {
httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
}
System.out.println(httpget + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
}
}

View File

@ -27,48 +27,45 @@
package org.apache.hc.client5.http.examples;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
/**
* This example demonstrates the recommended way of using API to make sure
* the underlying connection gets released back to the connection manager.
* This example demonstrates the recommended way of processing the HTTP response and releasing
* associated resources.
*/
public class ClientConnectionRelease {
public class ClientResponseProcessing {
public final static void main(final String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
final Result result = httpclient.execute(httpget, response -> {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
// Get hold of the response entity
final HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to bother about connection release
if (entity != null) {
try (final InputStream inStream = entity.getContent()) {
inStream.read();
// do something useful with the response
} catch (final IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
}
}
}
System.out.println(httpget + "->" + new StatusLine(response));
// Process response message and convert it into a value object
return new Result(response.getCode(), EntityUtils.toString(response.getEntity()));
});
System.out.println(result);
}
}
static class Result {
final int status;
final String content;
Result(final int status, final String content) {
this.status = status;
this.content = content;
}
}
}

View File

@ -1,73 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
/**
* This example demonstrates the use of the {@link HttpClientResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated resources.
*/
public class ClientWithResponseHandler {
public static void main(final String[] args) throws Exception {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
// Create a custom response handler
final HttpClientResponseHandler<String> responseHandler = response -> {
final int status = response.getCode();
if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
final HttpEntity entity = response.getEntity();
try {
return entity != null ? EntityUtils.toString(entity) : null;
} catch (final ParseException ex) {
throw new ClientProtocolException(ex);
}
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
final String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}
}

View File

@ -32,11 +32,12 @@ import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.io.CloseMode;
import org.junit.After;
import org.junit.Assert;
@ -84,7 +85,10 @@ public class TestHttpClientBuilderInterceptors {
@Test
public void testAddExecInterceptorLastShouldBeExecuted() throws IOException, HttpException {
final ClassicHttpRequest request = new HttpPost(uri);
final ClassicHttpResponse response = httpClient.execute(request);
final HttpResponse response = httpClient.execute(request, httpResponse -> {
EntityUtils.consume(httpResponse.getEntity());
return httpResponse;
});
Assert.assertEquals(200, response.getCode());
final Header testFilterHeader = response.getHeader("X-Test-Interceptor");
Assert.assertNotNull(testFilterHeader);