Move the code to httpclient

This commit is contained in:
2024-05-02 12:20:52 -04:00
parent 9c08c5559c
commit 002f2c8ede
73 changed files with 40 additions and 3184 deletions
@@ -0,0 +1,74 @@
package com.ossez.tlsversion;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
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;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.Timeout;
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultTlsConfig(TlsConfig.custom()
.setHandshakeTimeout(Timeout.ofSeconds(30))
.setSupportedProtocols(TLS.V_1_2, TLS.V_1_3)
.build())
.build();
return HttpClients.custom()
.setConnectionManager(cm)
.build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress()
.getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
socket.setEnabledProtocols(new String[] { "TLSv1.3" });
}
}
};
HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
return HttpClients.custom()
.setConnectionManager(connManager)
.build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
//return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
}
@@ -1,4 +1,4 @@
package com.baeldung.httpclient;
package com.ossez.httpclient;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.matchers.Times.exactly;
@@ -1,4 +1,4 @@
package com.baeldung.httpclient;
package com.ossez.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@@ -97,7 +97,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
@Test
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort);
final HttpHost proxy = new HttpHost("127.0.0.1", serverPort);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setRoutePlanner(routePlanner)
@@ -1,4 +1,4 @@
package com.baeldung.httpclient;
package com.ossez.httpclient;
import static org.assertj.core.api.Assertions.assertThat;
@@ -1,4 +1,4 @@
package com.baeldung.httpclient;
package com.ossez.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@@ -1,4 +1,4 @@
package com.baeldung.httpclient;
package com.ossez.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@@ -1,4 +1,4 @@
package com.baeldung.httpclient;
package com.ossez.httpclient;
import java.io.IOException;
@@ -1,4 +1,4 @@
package com.baeldung.httpclient.advancedconfig;
package com.ossez.httpclient.advancedconfig;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
@@ -1,4 +1,4 @@
package com.baeldung.httpclient.conn;
package com.ossez.httpclient.conn;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -1,4 +1,4 @@
package com.baeldung.httpclient.conn;
package com.ossez.httpclient.conn;
import java.io.IOException;
@@ -0,0 +1,61 @@
package com.ossez.httpclient.cookies;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.BasicHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.http.cookie.ClientCookie;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
class HttpClientGettingCookieValueUnitTest {
private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class);
private static final String SAMPLE_URL = "http://www.github.com/";
@Test
void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException {
HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_STORE, createCustomCookieStore());
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClientBuilder.create()
.build()) {
client.execute(request, context, new BasicHttpClientResponseHandler());
CookieStore cookieStore = context.getCookieStore();
Cookie customCookie = cookieStore.getCookies()
.stream()
.peek(cookie -> log.info("cookie name:{}", cookie.getName()))
.filter(cookie -> "custom_cookie".equals(cookie.getName()))
.findFirst()
.orElseThrow(IllegalStateException::new);
assertEquals("test_value", customCookie.getValue());
}
}
private BasicCookieStore createCustomCookieStore() {
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");
cookie.setDomain("github.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
return cookieStore;
}
}
@@ -0,0 +1,126 @@
package com.ossez.httpclient.expandUrl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hc.client5.http.classic.methods.HttpHead;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class HttpClientExpandUrlLiveTest {
private static CloseableHttpClient httpClient;
@BeforeAll
static void setup() {
httpClient = HttpClientBuilder.create()
.disableRedirectHandling()
.build();
}
@AfterAll
static void tearDown() throws IOException {
if (httpClient != null) {
httpClient.close();
}
}
@Test
void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
final String expectedResult = "https://www.baeldung.com/rest-versioning";
final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
assertThat(actualResult, equalTo(expectedResult));
}
@Test
void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
final String expectedResult = "https://www.baeldung.com/rest-versioning";
final String actualResult = expand("http://t.co/e4rDDbnzmk");
assertThat(actualResult, equalTo(expectedResult));
}
private String expand(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
newUrl = expandSingleLevel(originalUrl);
}
return newUrl;
}
final String expandSafe(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
newUrl = statusAndUrl.getRight();
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
if (isRedirect && alreadyVisited.contains(newUrl)) {
throw new IllegalStateException("Likely a redirect loop");
}
alreadyVisited.add(newUrl);
}
return newUrl;
}
private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
try {
HttpHead request = new HttpHead(url);
Pair<Integer, String> resp = httpClient.execute(request, response -> {
final int statusCode = response.getCode();
if (statusCode != 301 && statusCode != 302) {
return new ImmutablePair<>(statusCode, url);
}
final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
return new ImmutablePair<>(statusCode, newUrl);
});
return resp;
} catch (final IllegalArgumentException uriEx) {
return new ImmutablePair<>(500, url);
}
}
private String expandSingleLevel(final String url) throws IOException {
try {
HttpHead request = new HttpHead(url);
String expandedUrl = httpClient.execute(request, response -> {
final int statusCode = response.getCode();
if (statusCode != 301 && statusCode != 302) {
return url;
}
final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
return headers[0].getValue();
});
return expandedUrl;
} catch (final IllegalArgumentException uriEx) {
return url;
}
}
}
@@ -0,0 +1,72 @@
package com.ossez.httpclient.httpclient;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.apache.hc.client5.http.classic.HttpClient;
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.HttpClientBuilder;
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.io.entity.EntityUtils;
import org.junit.jupiter.api.Test;
class ApacheHttpClientUnitTest extends GetRequestMockServer {
@Test
void givenDeveloperUsedHttpClient_whenExecutingGetRequest_thenStatusIsOkButSonarReportsAnIssue() throws IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(serviceOneUrl);
httpClient.execute(httpGet, response -> {
assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
return response;
});
}
@Test
void givenDeveloperUsedCloseableHttpClient_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(serviceOneUrl);
httpClient.execute(httpGet, response -> {
assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
return response;
});
}
}
@Test
void givenDeveloperUsedHttpClientBuilder_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpGet = new HttpGet(serviceOneUrl);
httpClient.execute(httpGet, response -> {
assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
return response;
});
}
}
@Test
void givenDeveloperUsedSingleClient_whenExecutingTwoGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpGetOne = new HttpGet(serviceOneUrl);
httpClient.execute(httpGetOne, responseOne -> {
HttpEntity entityOne = responseOne.getEntity();
EntityUtils.consume(entityOne);
assertThat(responseOne.getCode()).isEqualTo(HttpStatus.SC_OK);
return responseOne;
});
HttpGet httpGetTwo = new HttpGet(serviceTwoUrl);
httpClient.execute(httpGetTwo, responseTwo -> {
HttpEntity entityTwo = httpGetTwo.getEntity();
EntityUtils.consume(entityTwo);
assertThat(responseTwo.getCode()).isEqualTo(HttpStatus.SC_OK);
return responseTwo;
});
}
}
}
@@ -0,0 +1,18 @@
package com.ossez.httpclient.httpclient;
import java.io.IOException;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
public final class ClientUtil {
private ClientUtil(){}
public static void closeClient(CloseableHttpClient client) throws IOException {
if (client == null) {
return;
}
client.close();
}
}
@@ -0,0 +1,78 @@
package com.ossez.httpclient.httpclient;
import org.apache.hc.core5.http.HttpStatus;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URISyntaxException;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.matchers.Times.exactly;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
public class GetRequestMockServer {
public static ClientAndServer mockServer;
public static String serviceOneUrl;
public static String serviceTwoUrl;
private static int serverPort;
public static final String SERVER_ADDRESS = "127.0.0.1";
public static final String PATH_ONE = "/test1";
public static final String PATH_TWO = "/test2";
public static final String METHOD = "GET";
@BeforeAll
static void startServer() throws IOException, URISyntaxException {
serverPort = getFreePort();
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
mockServer = startClientAndServer(serverPort);
mockGetRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
private static void mockGetRequest() {
new MockServerClient(SERVER_ADDRESS, serverPort)
.when(
request()
.withPath(PATH_ONE)
.withMethod(METHOD),
exactly(5)
)
.respond(
response()
.withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}")
);
new MockServerClient(SERVER_ADDRESS, serverPort)
.when(
request()
.withPath(PATH_TWO)
.withMethod(METHOD),
exactly(1)
)
.respond(
response()
.withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}")
);
}
private static int getFreePort () throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}
@@ -0,0 +1,211 @@
package com.ossez.httpclient.httpclient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
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.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.util.Timeout;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
class HttpClientCookBookLiveTest {
private static final String SAMPLE_GET_URL = "http://www.google.com";
private static final String SAMPLE_POST_URL = "http://www.github.com";
private CloseableHttpClient httpClient;
private CloseableHttpResponse response;
@BeforeEach
public final void before() {
httpClient = HttpClientBuilder.create().build();
}
@AfterEach
public final void after() throws IOException {
ClientUtil.closeClient(httpClient);
}
@Test
void givenGetRequestExecuted_thenCorrectStatusCode() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenGetRequestExecuted_thenCorrectContentMimeType() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
final String contentMimeType = ContentType.parse(response.getEntity().getContentType()).getMimeType();
assertThat(contentMimeType).isEqualTo(ContentType.TEXT_HTML.getMimeType());
return response;
}
);
}
@Test
void givenGetRequestExecuted_thenCorrectResponse() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
return response;
}
);
}
@Test
void whenConfigureTimeoutOnRequest_thenCorrectResponse() throws IOException {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMilliseconds(2000L))
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.build();
HttpGet request = new HttpGet(SAMPLE_GET_URL);
request.setConfig(requestConfig);
httpClient.execute(request,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenLowSocketTimeOut_whenExecutingRequestWithTimeout_thenException() throws IOException {
ConnectionConfig connConfig = ConnectionConfig.custom()
.setConnectTimeout(1000, TimeUnit.MILLISECONDS)
.setSocketTimeout(20, TimeUnit.MILLISECONDS)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMilliseconds(2000L))
.build();
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
cm.setConnectionConfig(connConfig);
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.build();
HttpGet request = new HttpGet(SAMPLE_GET_URL);
assertThrows(SocketTimeoutException.class, () -> {
httpClient.execute(request, resp -> resp);
});
}
@Test
void whenExecutingPostRequest_thenNoExceptions() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_POST_URL);
httpClient.execute(httpPost,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenParametersAddedToRequest_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_POST_URL);
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.defaultCharset()));
httpClient.execute(httpPost, response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
});
}
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
CloseableHttpClient client = HttpClientBuilder.create()
.disableRedirectHandling()
.build();
client.execute(new HttpGet("http://t.co/I5YYd9tddw"), response -> {
assertThat(response.getCode()).isEqualTo(301);
return response;
});
}
@Test
void givenHeadersAddedToRequest_thenCorrect() throws IOException {
HttpGet request = new HttpGet(SAMPLE_GET_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
httpClient.execute(request,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));
return response;
}
);
}
@Test
void givenAutoClosableClient_thenCorrect() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
httpClient.execute(httpGet, resp -> {
assertThat(resp.getCode()).isEqualTo(200);
return resp;
});
}
}
}
@@ -0,0 +1,27 @@
package com.ossez.httpclient.readresponsebodystring;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class ApacheHttpClient5UnitTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
void whenUseApacheHttpClient_thenCorrect() throws IOException {
HttpGet request = new HttpGet(DUMMY_URL);
try (CloseableHttpClient client = HttpClients.createDefault()) {
String response = client.execute(request, new BasicHttpClientResponseHandler());
logger.debug("Response -> {}", response);
}
}
}
@@ -0,0 +1,30 @@
package com.ossez.httpclient.readresponsebodystring;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.Test;
class HttpClientUnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(DUMMY_URL)).build();
// synchronous response
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
// asynchronous response
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
}
@@ -0,0 +1,36 @@
package com.ossez.httpclient.readresponsebodystring;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.jupiter.api.Test;
public class HttpUrlConnectionUnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
void whenUseHttpUrlConnection_thenCorrect() throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String currentLine;
while ((currentLine = in.readLine()) != null)
response.append(currentLine);
in.close();
assertNotNull(response.toString());
System.out.println("Response -> " + response.toString());
}
}
@@ -0,0 +1,16 @@
<configuration debug="false">
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date [%level] %logger - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.baeldung.httpclient.cookies" level="info"/>
<logger name="com.baeldung.httpclient.readresponsebodystring" level="INFO"/>
<logger name="org.apache.http" level="WARN"/>
<logger name="org.apache.hc.client5.http" level="WARN"/>
<root level="WARN">
<appender-ref ref="stdout"/>
</root>
</configuration>