use of okhttp3.Dispatcher in project okhttp by square.
the class CallTest method canceledBeforeResponseReadSignalsOnFailure.
@Test
public void canceledBeforeResponseReadSignalsOnFailure() throws Exception {
Request requestA = new Request.Builder().url(server.url("/a")).build();
final Call call = client.newCall(requestA);
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
call.cancel();
return new MockResponse().setBody("A");
}
});
call.enqueue(callback);
assertEquals("/a", server.takeRequest().getPath());
callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL", "Socket closed");
}
use of okhttp3.Dispatcher in project okhttp by square.
the class CallTest method canceledBeforeIOSignalsOnFailure.
/**
* This test puts a request in front of one that is to be canceled, so that it is canceled before
* I/O takes place.
*/
@Test
public void canceledBeforeIOSignalsOnFailure() throws Exception {
// Force requests to be executed serially.
okhttp3.Dispatcher dispatcher = new okhttp3.Dispatcher(client.dispatcher().executorService());
dispatcher.setMaxRequests(1);
client = client.newBuilder().dispatcher(dispatcher).build();
Request requestA = new Request.Builder().url(server.url("/a")).build();
Request requestB = new Request.Builder().url(server.url("/b")).build();
final Call callA = client.newCall(requestA);
final Call callB = client.newCall(requestB);
server.setDispatcher(new Dispatcher() {
char nextResponse = 'A';
@Override
public MockResponse dispatch(RecordedRequest request) {
callB.cancel();
return new MockResponse().setBody(Character.toString(nextResponse++));
}
});
callA.enqueue(callback);
callB.enqueue(callback);
assertEquals("/a", server.takeRequest().getPath());
callback.await(requestA.url()).assertBody("A");
// At this point we know the callback is ready, and that it will receive a cancel failure.
callback.await(requestB.url()).assertFailure("Canceled", "Socket closed");
}
use of okhttp3.Dispatcher in project okhttp by square.
the class OkHttpURLConnection method buildCall.
private Call buildCall() throws IOException {
if (call != null) {
return call;
}
connected = true;
if (doOutput) {
if (method.equals("GET")) {
// they are requesting a stream to write to. This implies a POST method
method = "POST";
} else if (!HttpMethod.permitsRequestBody(method)) {
throw new ProtocolException(method + " does not support writing");
}
}
if (requestHeaders.get("User-Agent") == null) {
requestHeaders.add("User-Agent", defaultUserAgent());
}
OutputStreamRequestBody requestBody = null;
if (HttpMethod.permitsRequestBody(method)) {
// Add a content type for the request body, if one isn't already present.
String contentType = requestHeaders.get("Content-Type");
if (contentType == null) {
contentType = "application/x-www-form-urlencoded";
requestHeaders.add("Content-Type", contentType);
}
boolean stream = fixedContentLength != -1L || chunkLength > 0;
long contentLength = -1L;
String contentLengthString = requestHeaders.get("Content-Length");
if (fixedContentLength != -1L) {
contentLength = fixedContentLength;
} else if (contentLengthString != null) {
contentLength = Long.parseLong(contentLengthString);
}
requestBody = stream ? new StreamedRequestBody(contentLength) : new BufferedRequestBody(contentLength);
requestBody.timeout().timeout(client.writeTimeoutMillis(), TimeUnit.MILLISECONDS);
}
Request request = new Request.Builder().url(Internal.instance.getHttpUrlChecked(getURL().toString())).headers(requestHeaders.build()).method(method, requestBody).build();
if (urlFilter != null) {
urlFilter.checkURLPermitted(request.url().url());
}
OkHttpClient.Builder clientBuilder = client.newBuilder();
clientBuilder.interceptors().clear();
clientBuilder.interceptors().add(UnexpectedException.INTERCEPTOR);
clientBuilder.networkInterceptors().clear();
clientBuilder.networkInterceptors().add(networkInterceptor);
// Use a separate dispatcher so that limits aren't impacted. But use the same executor service!
clientBuilder.dispatcher(new Dispatcher(client.dispatcher().executorService()));
// If we're currently not using caches, make sure the engine's client doesn't have one.
if (!getUseCaches()) {
clientBuilder.cache(null);
}
return call = clientBuilder.build().newCall(request);
}
use of okhttp3.Dispatcher in project okhttp by square.
the class WebSocketHttpTest method readTimeoutAppliesWithinFrames.
/**
* There's no read timeout when reading the first byte of a new frame. But as soon as we start
* reading a frame we enable the read timeout. In this test we have the server returning the first
* byte of a frame but no more frames.
*/
@Test
public void readTimeoutAppliesWithinFrames() throws IOException {
webServer.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
return upgradeResponse(request).setBody(// Truncated frame.
new Buffer().write(ByteString.decodeHex("81"))).removeHeader("Content-Length").setSocketPolicy(SocketPolicy.KEEP_OPEN);
}
});
WebSocket webSocket = newWebSocket();
clientListener.assertOpen();
clientListener.assertFailure(SocketTimeoutException.class, "timeout");
assertFalse(webSocket.close(1000, null));
}
use of okhttp3.Dispatcher in project amhttp by Eddieyuan123.
the class RequestManager method upload.
public <T> void upload(Context context, String url, CacheControl cacheControl, HashMap<String, String> headers, File file, String fileName, HashMap<String, String> params, Object tag, final OnUploadListener<T> listener) {
try {
IRequestBodyFactory requestBodyFactory = new RequestBodyFactoryImpl();
RequestBody requestBody = requestBodyFactory.buildRequestBody(file, fileName, params);
final Request request = new Request.Builder().cacheControl(cacheControl == null ? CacheControl.FORCE_NETWORK : cacheControl).headers(Headers.of(headers)).tag(tag == null ? context.hashCode() : tag).url(url).post(new ProgressRequestBody(requestBody, new ProgressRequestListener() {
@Override
public void onRequestProgress(final long bytesWritten, final long contentLength, final boolean done) {
if (listener != null) {
Dispatcher dispatcher = Dispatcher.getDispatcher(Looper.getMainLooper());
dispatcher.setRequestListener(listener);
Message message = Message.obtain();
message.what = MessageConstant.MESSAGE_UPLOAD_PROGRESS;
Bundle bundle = new Bundle();
bundle.putLong("bytesWritten", bytesWritten);
bundle.putLong("contentLength", contentLength);
bundle.putBoolean("done", done);
message.obj = bundle;
dispatcher.sendMessage(message);
}
}
})).build();
RequestUtils.enqueue(mOkHttpClient, request, listener);
} catch (Exception e) {
e.printStackTrace();
}
}
Aggregations