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;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
@ -7,10 +8,6 @@ import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import org.baeldung.okhttp.ProgressRequestWrapper;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
@ -19,33 +16,29 @@ import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
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;
@Before
public void init() {
client = new OkHttpClient();
client = new OkHttpClient();
}
@Test
public void whenUploadFile_thenCorrect() throws IOException {
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 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();
Request request = new Request.Builder()
.url(BASE_URL + "/users/upload")
.post(requestBody)
.build();
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build();
Call call = client.newCall(request);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@ -53,25 +46,18 @@ public class OkHttpFileUploadingLiveTest {
@Test
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
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 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();
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);
});
Request request = new Request.Builder()
.url(BASE_URL + "/users/upload")
.post(countingBody)
.build();
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build();
Call call = client.newCall(request);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));

View File

@ -1,14 +1,12 @@
package org.baeldung.okhttp;
import static org.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 org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
@ -16,9 +14,12 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
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;
@ -30,40 +31,42 @@ public class OkHttpGetLiveTest {
@Test
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);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
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");
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);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
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() {
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("OK");
}
@Override
public void onFailure(Call call, IOException e) {
fail();
}

View File

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

View File

@ -1,14 +1,12 @@
package org.baeldung.okhttp;
import static org.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 org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
import okhttp3.Credentials;
import okhttp3.FormBody;
@ -19,9 +17,12 @@ import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
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";
OkHttpClient client;
@ -29,77 +30,56 @@ public class OkHttpPostingLiveTest {
@Before
public void init() {
client = new OkHttpClient();
client = new OkHttpClient();
}
@Test
public void whenSendPostRequest_thenCorrect() throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("username", "test")
.add("password", "test")
.build();
final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
Request request = new Request.Builder()
.url(BASE_URL + "/users")
.post(formBody)
.build();
final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();
Call call = client.newCall(request);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
String postBody = "test post";
final String postBody = "test post";
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();
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();
Call call = client.newCall(request);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
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()
.url(BASE_URL + "/users/detail")
.post(body)
.build();
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
Call call = client.newCall(request);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
@Test
public void whenSendMultipartRequest_thenCorrect() throws IOException {
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 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();
Request request = new Request.Builder()
.url(BASE_URL + "/users/multipart")
.post(requestBody)
.build();
final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();
Call call = client.newCall(request);
Response response = call.execute();
final Call call = client.newCall(request);
final Response response = call.execute();
assertThat(response.code(), equalTo(200));
}

View File

@ -1,5 +1,6 @@
package org.baeldung.web.test;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
@ -31,7 +32,7 @@ public class RequestMappingLiveTest {
@Test
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