Merge pull request #811 from ivanp81/master

A Guide to OkHttp
This commit is contained in:
Jim Kerak 2016-11-07 14:49:13 -05:00 committed by GitHub
commit 4530246d17
2 changed files with 18 additions and 20 deletions

View File

@ -2,6 +2,7 @@ package org.baeldung.okhttp;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
@ -14,6 +15,9 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
//@RunWith(SpringJUnit4ClassRunner.class)
//@WebAppConfiguration
//@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/api-servlet.xml")
public class OkHttpGetLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
@ -54,7 +58,7 @@ public class OkHttpGetLiveTest {
}
@Test
public void whenAsynchronousGetRequest_thenCorrect() {
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
OkHttpClient client = new OkHttpClient();
@ -71,8 +75,10 @@ public class OkHttpGetLiveTest {
}
public void onFailure(Call call, IOException e) {
fail();
}
});
Thread.sleep(3000);
}
}

View File

@ -37,7 +37,7 @@ public class OkHttpMiscLiveTest {
response.close();
}
@Test
@Test(expected = IOException.class)
public void whenCancelRequest_thenCorrect() throws IOException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
@ -49,30 +49,22 @@ public class OkHttpMiscLiveTest {
.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(new Runnable() {
public void run() {
executor.schedule(() -> {
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f);
call.cancel();
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f);
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f);
call.cancel();
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f);
}
}, seconds, TimeUnit.SECONDS);
try {
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
Response response = call.execute();
logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
} catch (IOException e) {
logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e);
}
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
Response response = call.execute();
logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
}
@Test