This commit is contained in:
DOHA 2016-11-28 23:35:58 +02:00
parent 6e6c3e6e80
commit 753c71a399
5 changed files with 91 additions and 129 deletions

View File

@ -1,5 +1,6 @@
package org.baeldung.okhttp; package org.baeldung.okhttp;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
@ -7,10 +8,6 @@ import static org.junit.Assert.assertThat;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.baeldung.okhttp.ProgressRequestWrapper;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call; import okhttp3.Call;
import okhttp3.MediaType; import okhttp3.MediaType;
import okhttp3.MultipartBody; import okhttp3.MultipartBody;
@ -19,9 +16,12 @@ import okhttp3.Request;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import okhttp3.Response; import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
public class OkHttpFileUploadingLiveTest { public class OkHttpFileUploadingLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
OkHttpClient client; OkHttpClient client;
@ -33,19 +33,12 @@ public class OkHttpFileUploadingLiveTest {
@Test @Test
public void whenUploadFile_thenCorrect() throws IOException { public void whenUploadFile_thenCorrect() throws IOException {
RequestBody requestBody = new MultipartBody.Builder() 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();
.setType(MultipartBody.FORM)
.addFormDataPart("file", "file.txt",
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
.build();
Request request = new Request.Builder() final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build();
.url(BASE_URL + "/users/upload")
.post(requestBody)
.build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));
} }
@ -53,25 +46,18 @@ public class OkHttpFileUploadingLiveTest {
@Test @Test
public void whenGetUploadFileProgress_thenCorrect() throws IOException { public void whenGetUploadFileProgress_thenCorrect() throws IOException {
RequestBody requestBody = new MultipartBody.Builder() 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();
.setType(MultipartBody.FORM)
.addFormDataPart("file", "file.txt",
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
.build();
ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> { final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
float percentage = 100f * bytesWritten / contentLength; final float percentage = (100f * bytesWritten) / contentLength;
assertFalse(Float.compare(percentage, 100) > 0); assertFalse(Float.compare(percentage, 100) > 0);
}); });
Request request = new Request.Builder() final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build();
.url(BASE_URL + "/users/upload")
.post(countingBody)
.build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));

View File

@ -1,14 +1,12 @@
package org.baeldung.okhttp; package org.baeldung.okhttp;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call; import okhttp3.Call;
import okhttp3.Callback; import okhttp3.Callback;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
@ -16,9 +14,12 @@ import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
public class OkHttpGetLiveTest { public class OkHttpGetLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
OkHttpClient client; OkHttpClient client;
@ -30,40 +31,42 @@ public class OkHttpGetLiveTest {
@Test @Test
public void whenGetRequest_thenCorrect() throws IOException { public void whenGetRequest_thenCorrect() throws IOException {
Request request = new Request.Builder().url(BASE_URL + "/date").build(); final Request request = new Request.Builder().url(BASE_URL + "/date").build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));
} }
@Test @Test
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); final HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
urlBuilder.addQueryParameter("id", "1"); urlBuilder.addQueryParameter("id", "1");
String url = urlBuilder.build().toString(); final String url = urlBuilder.build().toString();
Request request = new Request.Builder().url(url).build(); final Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));
} }
@Test @Test
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
Request request = new Request.Builder().url(BASE_URL + "/date").build(); final Request request = new Request.Builder().url(BASE_URL + "/date").build();
Call call = client.newCall(request); final Call call = client.newCall(request);
call.enqueue(new Callback() { call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException { public void onResponse(Call call, Response response) throws IOException {
System.out.println("OK"); System.out.println("OK");
} }
@Override
public void onFailure(Call call, IOException e) { public void onFailure(Call call, IOException e) {
fail(); fail();
} }

View File

@ -1,27 +1,27 @@
package org.baeldung.okhttp; package org.baeldung.okhttp;
import okhttp3.*; import static org.baeldung.client.Consts.APPLICATION_PORT;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import okhttp3.Cache; import okhttp3.Cache;
import okhttp3.Call; import okhttp3.Call;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OkHttpMiscLiveTest { public class OkHttpMiscLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
OkHttpClient client; OkHttpClient client;
@ -34,25 +34,21 @@ public class OkHttpMiscLiveTest {
@Test @Test
public void whenSetRequestTimeout_thenFail() throws IOException { public void whenSetRequestTimeout_thenFail() throws IOException {
OkHttpClient clientWithTimeout = new OkHttpClient.Builder() final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build();
.readTimeout(1, TimeUnit.SECONDS)
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build(); .build();
Request request = new Request.Builder() final Call call = clientWithTimeout.newCall(request);
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. final Response response = call.execute();
.build();
Call call = clientWithTimeout.newCall(request);
Response response = call.execute();
response.close(); response.close();
} }
@Test(expected = IOException.class) @Test(expected = IOException.class)
public void whenCancelRequest_thenCorrect() throws IOException { public void whenCancelRequest_thenCorrect() throws IOException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Request request = new Request.Builder() final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build(); .build();
final int seconds = 1; final int seconds = 1;
@ -63,36 +59,32 @@ public class OkHttpMiscLiveTest {
// Schedule a job to cancel the call in 1 second. // Schedule a job to cancel the call in 1 second.
executor.schedule(() -> { executor.schedule(() -> {
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); logger.debug("Canceling call: " + ((System.nanoTime() - startNanos) / 1e9f));
call.cancel(); call.cancel();
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); logger.debug("Canceled call: " + ((System.nanoTime() - startNanos) / 1e9f));
}, seconds, TimeUnit.SECONDS); }, seconds, TimeUnit.SECONDS);
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); logger.debug("Executing call: " + ((System.nanoTime() - startNanos) / 1e9f));
Response response = call.execute(); final Response response = call.execute();
logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response); logger.debug("Call completed: " + ((System.nanoTime() - startNanos) / 1e9f), response);
} }
@Test @Test
public void whenSetResponseCache_thenCorrect() throws IOException { public void whenSetResponseCache_thenCorrect() throws IOException {
int cacheSize = 10 * 1024 * 1024; // 10 MiB final int cacheSize = 10 * 1024 * 1024; // 10 MiB
File cacheDirectory = new File("src/test/resources/cache"); final File cacheDirectory = new File("src/test/resources/cache");
Cache cache = new Cache(cacheDirectory, cacheSize); final Cache cache = new Cache(cacheDirectory, cacheSize);
OkHttpClient clientCached = new OkHttpClient.Builder() final OkHttpClient clientCached = new OkHttpClient.Builder().cache(cache).build();
.cache(cache)
.build();
Request request = new Request.Builder() final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
.url("http://publicobject.com/helloworld.txt")
.build();
Response response1 = clientCached.newCall(request).execute(); final Response response1 = clientCached.newCall(request).execute();
logResponse(response1); logResponse(response1);
Response response2 = clientCached.newCall(request).execute(); final Response response2 = clientCached.newCall(request).execute();
logResponse(response2); logResponse(response2);
} }

View File

@ -1,14 +1,12 @@
package org.baeldung.okhttp; package org.baeldung.okhttp;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call; import okhttp3.Call;
import okhttp3.Credentials; import okhttp3.Credentials;
import okhttp3.FormBody; import okhttp3.FormBody;
@ -19,9 +17,12 @@ import okhttp3.Request;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import okhttp3.Response; import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
public class OkHttpPostingLiveTest { public class OkHttpPostingLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest"; 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"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
OkHttpClient client; OkHttpClient client;
@ -34,72 +35,51 @@ public class OkHttpPostingLiveTest {
@Test @Test
public void whenSendPostRequest_thenCorrect() throws IOException { public void whenSendPostRequest_thenCorrect() throws IOException {
RequestBody formBody = new FormBody.Builder() final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
.add("username", "test")
.add("password", "test")
.build();
Request request = new Request.Builder() final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();
.url(BASE_URL + "/users")
.post(formBody)
.build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));
} }
@Test @Test
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
String postBody = "test post"; final String postBody = "test post";
Request request = new Request.Builder() 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"), postBody)).build();
.url(URL_SECURED_BY_BASIC_AUTHENTICATION)
.addHeader("Authorization", Credentials.basic("test", "test"))
.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody))
.build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));
} }
@Test @Test
public void whenPostJson_thenCorrect() throws IOException { public void whenPostJson_thenCorrect() throws IOException {
String json = "{\"id\":1,\"name\":\"John\"}"; final String json = "{\"id\":1,\"name\":\"John\"}";
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
Request request = new Request.Builder() final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
.url(BASE_URL + "/users/detail")
.post(body)
.build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));
} }
@Test @Test
public void whenSendMultipartRequest_thenCorrect() throws IOException { public void whenSendMultipartRequest_thenCorrect() throws IOException {
RequestBody requestBody = new MultipartBody.Builder() final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "test").addFormDataPart("password", "test")
.setType(MultipartBody.FORM) .addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
.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();
Request request = new Request.Builder() final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();
.url(BASE_URL + "/users/multipart")
.post(requestBody)
.build();
Call call = client.newCall(request); final Call call = client.newCall(request);
Response response = call.execute(); final Response response = call.execute();
assertThat(response.code(), equalTo(200)); assertThat(response.code(), equalTo(200));
} }

View File

@ -1,5 +1,6 @@
package org.baeldung.web.test; package org.baeldung.web.test;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import org.junit.Test; import org.junit.Test;
@ -31,7 +32,7 @@ public class RequestMappingLiveTest {
@Test @Test
public void givenAcceptHeader_whenGetFoos_thenOk() { public void givenAcceptHeader_whenGetFoos_thenOk() {
RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header New")); RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(containsString("Get some Foos with Header New"));
} }
@Test @Test