Merge pull request #7138 from amit2103/BAEL-15412
[BAEL-15412] - Moved article to libraries-http module
This commit is contained in:
@@ -36,14 +36,11 @@
|
||||
- [Introduction To Docx4J](http://www.baeldung.com/docx4j)
|
||||
- [Introduction to StreamEx](http://www.baeldung.com/streamex)
|
||||
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
|
||||
- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client)
|
||||
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
|
||||
- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
|
||||
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
|
||||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
|
||||
- [Introduction to Smooks](http://www.baeldung.com/smooks)
|
||||
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
|
||||
- [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan)
|
||||
- [Introduction to OpenCSV](http://www.baeldung.com/opencsv)
|
||||
- [A Guide to Unirest](http://www.baeldung.com/unirest)
|
||||
|
||||
@@ -28,13 +28,7 @@
|
||||
<version>${typesafe-akka.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
|
||||
<dependency>
|
||||
<groupId>org.asynchttpclient</groupId>
|
||||
<artifactId>async-http-client</artifactId>
|
||||
<version>${async.http.client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.beykery/neuroph/2.92 -->
|
||||
<dependency>
|
||||
<groupId>org.beykery</groupId>
|
||||
@@ -875,7 +869,6 @@
|
||||
<kafka.version>2.0.0</kafka.version>
|
||||
<smooks.version>1.7.0</smooks.version>
|
||||
<docker.version>3.0.14</docker.version>
|
||||
<async.http.client.version>2.2.0</async.http.client.version>
|
||||
<infinispan.version>9.1.5.Final</infinispan.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
<unirest.version>1.4.9</unirest.version>
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.baeldung.googlehttpclientguide;
|
||||
|
||||
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
|
||||
import com.google.api.client.http.HttpRequest;
|
||||
import com.google.api.client.http.HttpRequestFactory;
|
||||
import com.google.api.client.http.HttpResponse;
|
||||
import com.google.api.client.http.HttpTransport;
|
||||
import com.google.api.client.http.javanet.NetHttpTransport;
|
||||
import com.google.api.client.json.JsonFactory;
|
||||
import com.google.api.client.json.JsonObjectParser;
|
||||
import com.google.api.client.json.jackson2.JacksonFactory;
|
||||
import com.google.api.client.util.ExponentialBackOff;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class GitHubExample {
|
||||
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
|
||||
// static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
|
||||
static final JsonFactory JSON_FACTORY = new JacksonFactory();
|
||||
// static final JsonFactory JSON_FACTORY = new GsonFactory();
|
||||
|
||||
private static void run() throws Exception {
|
||||
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
|
||||
request.setParser(new JsonObjectParser(JSON_FACTORY));
|
||||
});
|
||||
GitHubUrl url = new GitHubUrl("https://api.github.com/users");
|
||||
url.per_page = 10;
|
||||
url.page = 1;
|
||||
HttpRequest request = requestFactory.buildGetRequest(url);
|
||||
ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
|
||||
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
|
||||
Type type = new TypeToken<List<User>>() {
|
||||
}.getType();
|
||||
List<User> users = (List<User>) request.execute().parseAs(type);
|
||||
System.out.println(users);
|
||||
url.appendRawPath("/eugenp");
|
||||
request = requestFactory.buildGetRequest(url);
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<HttpResponse> responseFuture = request.executeAsync(executor);
|
||||
User eugen = responseFuture.get().parseAs(User.class);
|
||||
System.out.println(eugen);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
run();
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.googlehttpclientguide;
|
||||
|
||||
import com.google.api.client.http.GenericUrl;
|
||||
import com.google.api.client.util.Key;
|
||||
|
||||
public class GitHubUrl extends GenericUrl {
|
||||
|
||||
public GitHubUrl(String encodedUrl) {
|
||||
super(encodedUrl);
|
||||
}
|
||||
|
||||
@Key
|
||||
public int per_page;
|
||||
|
||||
@Key
|
||||
public int page;
|
||||
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package com.baeldung.googlehttpclientguide;
|
||||
|
||||
import com.google.api.client.json.GenericJson;
|
||||
import com.google.api.client.util.Key;
|
||||
|
||||
public class User extends GenericJson {
|
||||
@Key
|
||||
private String login;
|
||||
@Key
|
||||
private long id;
|
||||
@Key
|
||||
private String url;
|
||||
@Key
|
||||
private String company;
|
||||
@Key
|
||||
private String blog;
|
||||
@Key
|
||||
private String email;
|
||||
|
||||
@Key("subscriptions_url")
|
||||
private String subscriptionsUrl;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = company;
|
||||
}
|
||||
|
||||
public String getBlog() {
|
||||
return blog;
|
||||
}
|
||||
|
||||
public void setBlog(String blog) {
|
||||
this.blog = blog;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
# Properties file which configures the operation of the JDK logging facility.
|
||||
# The system will look for this config file to be specified as a system property:
|
||||
# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties
|
||||
|
||||
# Set up the console handler (uncomment "level" to show more fine-grained messages)
|
||||
handlers = java.util.logging.ConsoleHandler
|
||||
java.util.logging.ConsoleHandler.level = ALL
|
||||
|
||||
# Set up logging of HTTP requests and responses (uncomment "level" to show)
|
||||
com.google.api.client.http.level = ALL
|
||||
@@ -1,204 +0,0 @@
|
||||
package com.baeldung.asynchttpclient;
|
||||
|
||||
import io.netty.handler.codec.http.HttpHeaders;
|
||||
import org.asynchttpclient.AsyncCompletionHandler;
|
||||
import org.asynchttpclient.AsyncHandler;
|
||||
import org.asynchttpclient.AsyncHttpClient;
|
||||
import org.asynchttpclient.AsyncHttpClientConfig;
|
||||
import org.asynchttpclient.BoundRequestBuilder;
|
||||
import org.asynchttpclient.Dsl;
|
||||
import org.asynchttpclient.HttpResponseBodyPart;
|
||||
import org.asynchttpclient.HttpResponseStatus;
|
||||
import org.asynchttpclient.ListenableFuture;
|
||||
import org.asynchttpclient.Request;
|
||||
import org.asynchttpclient.Response;
|
||||
import org.asynchttpclient.ws.WebSocket;
|
||||
import org.asynchttpclient.ws.WebSocketListener;
|
||||
import org.asynchttpclient.ws.WebSocketUpgradeHandler;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class AsyncHttpClientLiveTest {
|
||||
|
||||
private static AsyncHttpClient HTTP_CLIENT;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
AsyncHttpClientConfig clientConfig = Dsl.config().setConnectTimeout(15000).setRequestTimeout(15000).build();
|
||||
HTTP_CLIENT = Dsl.asyncHttpClient(clientConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeSyncGetRequest() {
|
||||
|
||||
BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
|
||||
|
||||
Future<Response> responseFuture = boundGetRequest.execute();
|
||||
try {
|
||||
Response response = responseFuture.get(5000, TimeUnit.MILLISECONDS);
|
||||
assertNotNull(response);
|
||||
assertEquals(200, response.getStatusCode());
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequest() {
|
||||
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncCompletionHandler<Integer>() {
|
||||
@Override
|
||||
public Integer onCompleted(Response response) {
|
||||
|
||||
int resposeStatusCode = response.getStatusCode();
|
||||
assertEquals(200, resposeStatusCode);
|
||||
return resposeStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
// execute a bound GET request
|
||||
BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
|
||||
|
||||
boundGetRequest.execute(new AsyncCompletionHandler<Integer>() {
|
||||
@Override
|
||||
public Integer onCompleted(Response response) {
|
||||
int resposeStatusCode = response.getStatusCode();
|
||||
assertEquals(200, resposeStatusCode);
|
||||
return resposeStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequestWithAsyncHandler() {
|
||||
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncHandler<Integer>() {
|
||||
|
||||
int responseStatusCode = -1;
|
||||
|
||||
@Override
|
||||
public State onStatusReceived(HttpResponseStatus responseStatus) {
|
||||
responseStatusCode = responseStatus.getStatusCode();
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onHeadersReceived(HttpHeaders headers) {
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) {
|
||||
return State.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onThrowable(Throwable t) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer onCompleted() {
|
||||
assertEquals(200, responseStatusCode);
|
||||
return responseStatusCode;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpClient_executeAsyncGetRequestWithListanableFuture() {
|
||||
// execute an unbound GET request
|
||||
Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
|
||||
|
||||
ListenableFuture<Response> listenableFuture = HTTP_CLIENT.executeRequest(unboundGetRequest);
|
||||
listenableFuture.addListener(() -> {
|
||||
Response response;
|
||||
try {
|
||||
response = listenableFuture.get(5000, TimeUnit.MILLISECONDS);
|
||||
assertEquals(200, response.getStatusCode());
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, Executors.newCachedThreadPool());
|
||||
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWebSocketClient_tryToConnect() {
|
||||
|
||||
WebSocketUpgradeHandler.Builder upgradeHandlerBuilder = new WebSocketUpgradeHandler.Builder();
|
||||
WebSocketUpgradeHandler wsHandler = upgradeHandlerBuilder.addWebSocketListener(new WebSocketListener() {
|
||||
@Override
|
||||
public void onOpen(WebSocket websocket) {
|
||||
// WebSocket connection opened
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(WebSocket websocket, int code, String reason) {
|
||||
// WebSocket connection closed
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable t) {
|
||||
// WebSocket connection error
|
||||
assertTrue(t.getMessage().contains("Request timeout"));
|
||||
}
|
||||
}).build();
|
||||
|
||||
WebSocket WEBSOCKET_CLIENT = null;
|
||||
try {
|
||||
WEBSOCKET_CLIENT = Dsl.asyncHttpClient().prepareGet("ws://localhost:5590/websocket").addHeader("header_name", "header_value").addQueryParam("key", "value").setRequestTimeout(5000).execute(wsHandler).get();
|
||||
|
||||
if (WEBSOCKET_CLIENT.isOpen()) {
|
||||
WEBSOCKET_CLIENT.sendPingFrame();
|
||||
WEBSOCKET_CLIENT.sendTextFrame("test message");
|
||||
WEBSOCKET_CLIENT.sendBinaryFrame(new byte[] { 't', 'e', 's', 't' });
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (WEBSOCKET_CLIENT != null && WEBSOCKET_CLIENT.isOpen()) {
|
||||
WEBSOCKET_CLIENT.sendCloseFrame(200, "OK");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user