Merge branch 'master' into bael-16656

This commit is contained in:
Josh Cummings
2019-10-26 15:37:05 -06:00
committed by GitHub
parent db85c8f275
commit 0be2175c89
20539 changed files with 1643630 additions and 0 deletions
@@ -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);
}
}