[BAEL-15412] - Moved article to libraries-http module
This commit is contained in:
7
libraries-http/README.md
Normal file
7
libraries-http/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp)
|
||||
- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client)
|
||||
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
|
||||
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
|
||||
81
libraries-http/pom.xml
Normal file
81
libraries-http/pom.xml
Normal file
@@ -0,0 +1,81 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>libraries-http</artifactId>
|
||||
<name>libraries-http</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Dependencies for response decoder with okhttp -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${com.squareup.okhttp3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Dependencies for google http client -->
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client</artifactId>
|
||||
<version>${googleclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client-jackson2</artifactId>
|
||||
<version>${googleclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.http-client</groupId>
|
||||
<artifactId>google-http-client-gson</artifactId>
|
||||
<version>${googleclient.version}</version>
|
||||
</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>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.5</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>mockwebserver</artifactId>
|
||||
<version>${com.squareup.okhttp3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.2</assertj.version>
|
||||
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
|
||||
<googleclient.version>1.23.0</googleclient.version>
|
||||
<async.http.client.version>2.2.0</async.http.client.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,56 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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 + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 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
|
||||
13
libraries-http/src/main/resources/logback.xml
Normal file
13
libraries-http/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,204 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.client;
|
||||
|
||||
public interface Consts {
|
||||
int APPLICATION_PORT = 8082;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
public class DefaultContentTypeInterceptor implements Interceptor {
|
||||
|
||||
private final String contentType;
|
||||
|
||||
public DefaultContentTypeInterceptor(String contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
public Response intercept(Interceptor.Chain chain) throws IOException {
|
||||
|
||||
Request originalRequest = chain.request();
|
||||
Request requestWithUserAgent = originalRequest.newBuilder().header("Content-Type", contentType).build();
|
||||
|
||||
return chain.proceed(requestWithUserAgent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import static com.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Execute <code>spring-rest</code> module before running this live test
|
||||
*/
|
||||
public class OkHttpFileUploadingLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadFile_thenCorrect() throws IOException {
|
||||
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
|
||||
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
|
||||
|
||||
final float percentage = (100f * bytesWritten) / contentLength;
|
||||
assertFalse(Float.compare(percentage, 100) > 0);
|
||||
});
|
||||
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import static com.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Callback;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Execute <code>spring-rest</code> module before running this live test
|
||||
*/
|
||||
public class OkHttpGetLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequest_thenCorrect() throws IOException {
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
|
||||
final HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
|
||||
urlBuilder.addQueryParameter("id", "1");
|
||||
|
||||
final String url = urlBuilder.build().toString();
|
||||
|
||||
final Request request = new Request.Builder().url(url).build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
|
||||
call.enqueue(new Callback() {
|
||||
@Override
|
||||
public void onResponse(Call call, Response response) throws IOException {
|
||||
System.out.println("OK");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
fail();
|
||||
}
|
||||
});
|
||||
|
||||
Thread.sleep(3000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
public class OkHttpHeaderLiveTest {
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetHeader_thenCorrect() throws IOException {
|
||||
Request request = new Request.Builder().url(SAMPLE_URL).addHeader("Content-Type", "application/json").build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
response.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetDefaultHeader_thenCorrect() throws IOException {
|
||||
|
||||
OkHttpClient clientWithInterceptor = new OkHttpClient.Builder().addInterceptor(new DefaultContentTypeInterceptor("application/json")).build();
|
||||
|
||||
Request request = new Request.Builder().url(SAMPLE_URL).build();
|
||||
|
||||
Call call = clientWithInterceptor.newCall(request);
|
||||
Response response = call.execute();
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import static com.baeldung.client.Consts.APPLICATION_PORT;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import okhttp3.Cache;
|
||||
import okhttp3.Call;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Execute <code>spring-rest</code> module before running this live test
|
||||
*/
|
||||
public class OkHttpMiscLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test(expected = SocketTimeoutException.class)
|
||||
public void whenSetRequestTimeout_thenFail() throws IOException {
|
||||
final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build();
|
||||
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
|
||||
final Call call = clientWithTimeout.newCall(request);
|
||||
final Response response = call.execute();
|
||||
response.close();
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void whenCancelRequest_thenCorrect() throws IOException {
|
||||
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
|
||||
final int seconds = 1;
|
||||
final long startNanos = System.nanoTime();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
|
||||
// Schedule a job to cancel the call in 1 second.
|
||||
executor.schedule(() -> {
|
||||
|
||||
logger.debug("Canceling call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
call.cancel();
|
||||
logger.debug("Canceled call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
|
||||
}, seconds, TimeUnit.SECONDS);
|
||||
|
||||
logger.debug("Executing call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
final Response response = call.execute();
|
||||
logger.debug("Call completed: " + ((System.nanoTime() - startNanos) / 1e9f), response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetResponseCache_thenCorrect() throws IOException {
|
||||
|
||||
final int cacheSize = 10 * 1024 * 1024; // 10 MiB
|
||||
final File cacheDirectory = new File("src/test/resources/cache");
|
||||
final Cache cache = new Cache(cacheDirectory, cacheSize);
|
||||
|
||||
final OkHttpClient clientCached = new OkHttpClient.Builder().cache(cache).build();
|
||||
|
||||
final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
|
||||
|
||||
final Response response1 = clientCached.newCall(request).execute();
|
||||
logResponse(response1);
|
||||
|
||||
final Response response2 = clientCached.newCall(request).execute();
|
||||
logResponse(response2);
|
||||
}
|
||||
|
||||
private void logResponse(Response response) throws IOException {
|
||||
|
||||
logger.debug("Response response: " + response);
|
||||
logger.debug("Response cache response: " + response.cacheResponse());
|
||||
logger.debug("Response network response: " + response.networkResponse());
|
||||
logger.debug("Response responseBody: " + response.body().string());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import static com.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Credentials;
|
||||
import okhttp3.FormBody;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Execute <code>spring-rest</code> module before running this live test
|
||||
*/
|
||||
public class OkHttpPostingLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequest_thenCorrect() throws IOException {
|
||||
final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
|
||||
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
|
||||
final String postBody = "test post";
|
||||
|
||||
final Request request = new Request.Builder().url(URL_SECURED_BY_BASIC_AUTHENTICATION).addHeader("Authorization", Credentials.basic("test", "test")).post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "test post")).build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostJson_thenCorrect() throws IOException {
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
|
||||
final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"id\":1,\"name\":\"John\"}");
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMultipartRequest_thenCorrect() throws IOException {
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "test").addFormDataPart("password", "test")
|
||||
.addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();
|
||||
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
public class OkHttpRedirectLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenSetFollowRedirects_thenNotRedirected() throws IOException {
|
||||
|
||||
OkHttpClient client = new OkHttpClient().newBuilder().followRedirects(false).build();
|
||||
|
||||
Request request = new Request.Builder().url("http://t.co/I5YYd9tddw").build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(301));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.okhttp;
|
||||
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.MediaType;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okio.Buffer;
|
||||
import okio.BufferedSink;
|
||||
import okio.ForwardingSink;
|
||||
import okio.Okio;
|
||||
import okio.Sink;
|
||||
|
||||
public class ProgressRequestWrapper extends RequestBody {
|
||||
|
||||
protected RequestBody delegate;
|
||||
protected ProgressListener listener;
|
||||
|
||||
protected CountingSink countingSink;
|
||||
|
||||
public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) {
|
||||
this.delegate = delegate;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MediaType contentType() {
|
||||
return delegate.contentType();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long contentLength() throws IOException {
|
||||
return delegate.contentLength();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(BufferedSink sink) throws IOException {
|
||||
|
||||
BufferedSink bufferedSink;
|
||||
|
||||
countingSink = new CountingSink(sink);
|
||||
bufferedSink = Okio.buffer(countingSink);
|
||||
|
||||
delegate.writeTo(bufferedSink);
|
||||
|
||||
bufferedSink.flush();
|
||||
}
|
||||
|
||||
protected final class CountingSink extends ForwardingSink {
|
||||
|
||||
private long bytesWritten = 0;
|
||||
|
||||
public CountingSink(Sink delegate) {
|
||||
super(delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(Buffer source, long byteCount) throws IOException {
|
||||
|
||||
super.write(source, byteCount);
|
||||
|
||||
bytesWritten += byteCount;
|
||||
listener.onRequestProgress(bytesWritten, contentLength());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public interface ProgressListener {
|
||||
|
||||
void onRequestProgress(long bytesWritten, long contentLength);
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user