Search in sources :

Example 26 with okhttp3

use of okhttp3 in project fresco by facebook.

the class OkHttpNetworkFetcher method fetchWithRequest.

protected void fetchWithRequest(final OkHttpNetworkFetchState fetchState, final Callback callback, final Request request) {
    final Call call = mCallFactory.newCall(request);
    fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks() {

        @Override
        public void onCancellationRequested() {
            if (Looper.myLooper() != Looper.getMainLooper()) {
                call.cancel();
            } else {
                mCancellationExecutor.execute(new Runnable() {

                    @Override
                    public void run() {
                        call.cancel();
                    }
                });
            }
        }
    });
    call.enqueue(new okhttp3.Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            fetchState.responseTime = SystemClock.elapsedRealtime();
            final ResponseBody body = response.body();
            try {
                if (!response.isSuccessful()) {
                    handleException(call, new IOException("Unexpected HTTP code " + response), callback);
                    return;
                }
                long contentLength = body.contentLength();
                if (contentLength < 0) {
                    contentLength = 0;
                }
                callback.onResponse(body.byteStream(), (int) contentLength);
            } catch (Exception e) {
                handleException(call, e, callback);
            } finally {
                try {
                    body.close();
                } catch (Exception e) {
                    FLog.w(TAG, "Exception when closing response body", e);
                }
            }
        }

        @Override
        public void onFailure(Call call, IOException e) {
            handleException(call, e, callback);
        }
    });
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) IOException(java.io.IOException) IOException(java.io.IOException) BaseProducerContextCallbacks(com.facebook.imagepipeline.producers.BaseProducerContextCallbacks) ResponseBody(okhttp3.ResponseBody)

Example 27 with okhttp3

use of okhttp3 in project okhttputils by hongyangAndroid.

the class OkHttpUtils method execute.

public void execute(final RequestCall requestCall, Callback callback) {
    if (callback == null)
        callback = Callback.CALLBACK_DEFAULT;
    final Callback finalCallback = callback;
    final int id = requestCall.getOkHttpRequest().getId();
    requestCall.getCall().enqueue(new okhttp3.Callback() {

        @Override
        public void onFailure(Call call, final IOException e) {
            sendFailResultCallback(call, e, finalCallback, id);
        }

        @Override
        public void onResponse(final Call call, final Response response) {
            try {
                if (call.isCanceled()) {
                    sendFailResultCallback(call, new IOException("Canceled!"), finalCallback, id);
                    return;
                }
                if (!finalCallback.validateReponse(response, id)) {
                    sendFailResultCallback(call, new IOException("request failed , reponse's code is : " + response.code()), finalCallback, id);
                    return;
                }
                Object o = finalCallback.parseNetworkResponse(response, id);
                sendSuccessResultCallback(o, finalCallback, id);
            } catch (Exception e) {
                sendFailResultCallback(call, e, finalCallback, id);
            } finally {
                if (response.body() != null)
                    response.body().close();
            }
        }
    });
}
Also used : Response(okhttp3.Response) RequestCall(com.zhy.http.okhttp.request.RequestCall) Call(okhttp3.Call) Callback(com.zhy.http.okhttp.callback.Callback) IOException(java.io.IOException) IOException(java.io.IOException)

Example 28 with okhttp3

use of okhttp3 in project retrofit by square.

the class CallTest method conversionProblemIncomingMaskedByConverterIsUnwrapped.

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = //
    new OkHttpClient.Builder().addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {

                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    }).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client).addConverterFactory(new ToStringConverterFactory() {

        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            return new Converter<ResponseBody, String>() {

                @Override
                public String convert(ResponseBody value) throws IOException {
                    try {
                        return value.string();
                    } catch (IOException e) {
                        // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                        throw new RuntimeException("wrapper", e);
                    }
                }
            };
        }
    }).build();
    Service example = retrofit.create(Service.class);
    server.enqueue(new MockResponse().setBody("Hi"));
    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) OkHttpClient(okhttp3.OkHttpClient) ForwardingSource(okio.ForwardingSource) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) Interceptor(okhttp3.Interceptor) BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Example 29 with okhttp3

use of okhttp3 in project retrofit by square.

the class OkHttpCall method parseResponse.

Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body();
    // Remove the body's source (the only stateful object) so we can pass the response along.
    rawResponse = rawResponse.newBuilder().body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();
    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
        try {
            // Buffer the entire body to avoid future I/O.
            ResponseBody bufferedBody = Utils.buffer(rawBody);
            return Response.error(bufferedBody, rawResponse);
        } finally {
            rawBody.close();
        }
    }
    if (code == 204 || code == 205) {
        rawBody.close();
        return Response.success(null, rawResponse);
    }
    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {
        T body = serviceMethod.toResponse(catchingBody);
        return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
        // If the underlying source threw an exception, propagate that rather than indicating it was
        // a runtime exception.
        catchingBody.throwIfCaught();
        throw e;
    }
}
Also used : ResponseBody(okhttp3.ResponseBody)

Example 30 with okhttp3

use of okhttp3 in project retrofit by square.

the class RequestBuilderTest method headerParamList.

@Test
public void headerParamList() {
    class Example {

        //
        @GET("/foo/bar/")
        Call<ResponseBody> method(@Header("foo") List<String> kit) {
            return null;
        }
    }
    Request request = buildRequest(Example.class, Arrays.asList("bar", null, "baz"));
    assertThat(request.method()).isEqualTo("GET");
    okhttp3.Headers headers = request.headers();
    assertThat(headers.size()).isEqualTo(2);
    assertThat(headers.values("foo")).containsExactly("bar", "baz");
    assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
    assertThat(request.body()).isNull();
}
Also used : Header(retrofit2.http.Header) Request(okhttp3.Request) List(java.util.List) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Aggregations

Request (okhttp3.Request)25 IOException (java.io.IOException)20 Test (org.junit.Test)16 ResponseBody (okhttp3.ResponseBody)12 OkHttpClient (okhttp3.OkHttpClient)10 Response (okhttp3.Response)9 RequestBody (okhttp3.RequestBody)8 MockResponse (okhttp3.mockwebserver.MockResponse)8 Call (okhttp3.Call)5 Interceptor (okhttp3.Interceptor)5 Map (java.util.Map)4 Retrofit (retrofit2.Retrofit)4 Header (retrofit2.http.Header)4 List (java.util.List)3 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)3 Response (retrofit2.Response)3 ToStringConverterFactory (retrofit2.helpers.ToStringConverterFactory)3 HashMap (java.util.HashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Level (java.util.logging.Level)2