Search in sources :

Example 11 with ForwardingSource

use of okio.ForwardingSource in project okhttp by square.

the class ResponseBodyTest method stringClosesUnderlyingSource.

@Test
public void stringClosesUnderlyingSource() throws IOException {
    final AtomicBoolean closed = new AtomicBoolean();
    ResponseBody body = new ResponseBody() {

        @Override
        public MediaType contentType() {
            return null;
        }

        @Override
        public long contentLength() {
            return 5;
        }

        @Override
        public BufferedSource source() {
            Buffer source = new Buffer().writeUtf8("hello");
            return Okio.buffer(new ForwardingSource(source) {

                @Override
                public void close() throws IOException {
                    closed.set(true);
                    super.close();
                }
            });
        }
    };
    assertEquals("hello", body.string());
    assertTrue(closed.get());
}
Also used : Buffer(okio.Buffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ForwardingSource(okio.ForwardingSource) IOException(java.io.IOException) Test(org.junit.Test)

Example 12 with ForwardingSource

use of okio.ForwardingSource 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 13 with ForwardingSource

use of okio.ForwardingSource in project OkHttp3 by MrZhousf.

the class ProgressResponseBody method source.

private Source source(Source source) {
    return new ForwardingSource(source) {

        long totalBytesRead = 0L;

        long contentLength = 0L;

        ProgressCallback progressCallback;

        int lastPercent = 0;

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long bytesRead = super.read(sink, byteCount);
            if (totalBytesRead == 0) {
                totalBytesRead = downloadFileInfo.getCompletedSize();
                Log.d(requestTag + "[" + timeStamp + "]", "从节点[" + totalBytesRead + "]开始下载" + downloadFileInfo.getSaveFileNameWithExtension());
            }
            if (contentLength == 0) {
                // 文件总长度=当前需要下载长度+已完成长度
                contentLength = contentLength() + totalBytesRead;
            }
            totalBytesRead += bytesRead != -1 ? bytesRead : 0;
            if (null == progressCallback)
                progressCallback = downloadFileInfo.getProgressCallback();
            if (null != progressCallback) {
                int percent = (int) ((100 * totalBytesRead) / contentLength);
                // 每处理1%则立即回调
                if (percent != lastPercent) {
                    lastPercent = percent;
                    progressCallback.onProgressAsync(percent, totalBytesRead, contentLength, totalBytesRead == -1);
                    // 主线程回调
                    Message msg = new ProgressMessage(OkMainHandler.PROGRESS_CALLBACK, progressCallback, percent, totalBytesRead, contentLength, bytesRead == -1, requestTag).build();
                    OkMainHandler.getInstance().sendMessage(msg);
                }
            }
            return bytesRead;
        }
    };
}
Also used : Buffer(okio.Buffer) ProgressMessage(com.okhttplib.bean.ProgressMessage) Message(android.os.Message) ProgressMessage(com.okhttplib.bean.ProgressMessage) ProgressCallback(com.okhttplib.callback.ProgressCallback) ForwardingSource(okio.ForwardingSource)

Aggregations

ForwardingSource (okio.ForwardingSource)13 Buffer (okio.Buffer)10 IOException (java.io.IOException)9 Test (org.junit.Test)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Source (okio.Source)2 Message (android.os.Message)1 HttpCacheRecord (com.apollographql.apollo.api.cache.http.HttpCacheRecord)1 ProgressMessage (com.okhttplib.bean.ProgressMessage)1 ProgressCallback (com.okhttplib.callback.ProgressCallback)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 Type (java.lang.reflect.Type)1 Interceptor (okhttp3.Interceptor)1 OkHttpClient (okhttp3.OkHttpClient)1 Response (okhttp3.Response)1 ResponseBody (okhttp3.ResponseBody)1 MockResponse (okhttp3.mockwebserver.MockResponse)1 BufferedSource (okio.BufferedSource)1