Example usage for com.squareup.okhttp ResponseBody close

List of usage examples for com.squareup.okhttp ResponseBody close

Introduction

In this page you can find the example usage for com.squareup.okhttp ResponseBody close.

Prototype

@Override
    public void close() throws IOException 

Source Link

Usage

From source file:BenchMarkTest.java

License:Open Source License

void doOkHttpRequest() {
    ++okhttp_task_cnt;//w  w  w. j av  a2s  .  c  o m
    try {
        OkHttpClient client = new OkHttpClient();

        Main.HelloRequest req = new Main.HelloRequest();
        req.user = "okhttp";
        req.text = Integer.toString((int) okhttp_task_cnt);
        //Benchmark 64KB/128KB
        /*req.dumpContent = new byte[64*1024];
        Random rand = new Random();
        rand.nextBytes(req.dumpContent);*/

        final byte[] flatArray = new byte[req.getSerializedSize()];
        final CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(flatArray);
        req.writeTo(output);
        RequestBody reqBody = RequestBody.create(MediaType.parse("application/octet-stream"), flatArray);

        //normal request
        Request request = new Request.Builder().url("http://118.89.24.72:8080/mars/hello2")
                .addHeader("Cache-Control", "no-cache").addHeader("Content-Type", "application/octet-stream")
                .addHeader("Connection", "close").addHeader("Accept", "*/*").post(reqBody).build();

        okhttp_task_time = System.currentTimeMillis();
        // Execute the request and retrieve the response.
        Response response = client.newCall(request).execute();

        ResponseBody body = response.body();
        Main.HelloResponse helloResp = Main.HelloResponse.parseFrom(body.bytes());
        body.close();

        long curr = System.currentTimeMillis();
        okhttp_suc_time += curr - okhttp_task_time;
        ++okhttp_task_suc;
        //Log.i(TAG, "http type:" + type + ", suc cost:" + (curr - okhttp_task_time) + ", count:" + okhttp_task_cnt + ", suc count:" + okhttp_task_suc + ", ctn:" + helloResp.errmsg);
    } catch (Exception e) {
        Log.e(TAG, "http fail cost:" + (System.currentTimeMillis() - okhttp_task_time) + ", count:"
                + okhttp_task_cnt);
    }
}

From source file:co.rsk.rpc.netty.Web3WebSocketServerTest.java

License:Open Source License

@Test
public void smokeTest() throws Exception {
    Web3 web3Mock = mock(Web3.class);
    String mockResult = "output";
    when(web3Mock.web3_sha3(anyString())).thenReturn(mockResult);

    int randomPort = 9998;//new ServerSocket(0).getLocalPort();

    List<ModuleDescription> filteredModules = Collections.singletonList(
            new ModuleDescription("web3", "1.0", true, Collections.emptyList(), Collections.emptyList()));
    RskJsonRpcHandler handler = new RskJsonRpcHandler(null, new JacksonBasedRpcSerializer());
    JsonRpcWeb3ServerHandler serverHandler = new JsonRpcWeb3ServerHandler(web3Mock, filteredModules);

    Web3WebSocketServer websocketServer = new Web3WebSocketServer(InetAddress.getLoopbackAddress(), randomPort,
            handler, serverHandler);/*from  w ww  .  j a va2 s.  com*/
    websocketServer.start();

    OkHttpClient wsClient = new OkHttpClient();
    Request wsRequest = new Request.Builder().url("ws://localhost:" + randomPort + "/websocket").build();
    WebSocketCall wsCall = WebSocketCall.create(wsClient, wsRequest);

    CountDownLatch wsAsyncResultLatch = new CountDownLatch(1);
    CountDownLatch wsAsyncCloseLatch = new CountDownLatch(1);
    AtomicReference<Exception> failureReference = new AtomicReference<>();
    wsCall.enqueue(new WebSocketListener() {

        private WebSocket webSocket;

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            wsExecutor.submit(() -> {
                RequestBody body = RequestBody.create(WebSocket.TEXT, getJsonRpcDummyMessage());
                try {
                    this.webSocket = webSocket;
                    this.webSocket.sendMessage(body);
                    this.webSocket.close(1000, null);
                } catch (IOException e) {
                    failureReference.set(e);
                }
            });
        }

        @Override
        public void onFailure(IOException e, Response response) {
            failureReference.set(e);
        }

        @Override
        public void onMessage(ResponseBody message) throws IOException {
            JsonNode jsonRpcResponse = OBJECT_MAPPER.readTree(message.bytes());
            assertThat(jsonRpcResponse.at("/result").asText(), is(mockResult));
            message.close();
            wsAsyncResultLatch.countDown();
        }

        @Override
        public void onPong(Buffer payload) {
        }

        @Override
        public void onClose(int code, String reason) {
            wsAsyncCloseLatch.countDown();
        }
    });

    if (!wsAsyncResultLatch.await(10, TimeUnit.SECONDS)) {
        fail("Result timed out");
    }

    if (!wsAsyncCloseLatch.await(10, TimeUnit.SECONDS)) {
        fail("Close timed out");
    }

    websocketServer.stop();

    Exception failure = failureReference.get();
    if (failure != null) {
        failure.printStackTrace();
        fail(failure.getMessage());
    }
}

From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetcher.java

License:Open Source License

@Override
public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) {
    fetchState.submitTime = SystemClock.elapsedRealtime();
    final Uri uri = fetchState.getUri();
    final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build())
            .url(uri.toString()).get().build();
    final Call call = mOkHttpClient.newCall(request);

    fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks() {
        @Override/*from w  ww  . ja v a  2 s. co m*/
        public void onCancellationRequested() {
            if (Looper.myLooper() != Looper.getMainLooper()) {
                call.cancel();
            } else {
                mCancellationExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        call.cancel();
                    }
                });
            }
        }
    });

    call.enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onResponse(Response response) {
            fetchState.responseTime = SystemClock.elapsedRealtime();
            final ResponseBody body = response.body();
            try {
                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(final Request request, final IOException e) {
            handleException(call, e, callback);
        }
    });
}

From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetchProducer.java

License:Open Source License

@Override
protected void fetchImage(final NfpRequestState requestState) {
    final Uri uri = requestState.getUri();
    final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build())
            .url(uri.toString()).get().build();
    final Call call = mOkHttpClient.newCall(request);

    if (mCancellable) {
        requestState.getContext().addCallbacks(new BaseProducerContextCallbacks() {
            @Override/* w  w  w.j  a v a2s . c  o m*/
            public void onCancellationRequested() {
                call.cancel();
            }
        });
    }

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Response response) {
            final ResponseBody body = response.body();
            try {
                long contentLength = body.contentLength();
                if (contentLength < 0) {
                    contentLength = 0;
                }
                processResult(requestState, body.byteStream(), (int) contentLength, false);
            } catch (IOException ioe) {
                handleException(call, requestState, ioe);
            } finally {
                try {
                    body.close();
                } catch (IOException ioe) {
                    FLog.w(TAG, "Exception when closing response body", ioe);
                }
            }
        }

        @Override
        public void onFailure(final Request request, final IOException e) {
            handleException(call, requestState, e);
        }
    });
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void uploadFile(final String url, final File file, final long startOffset,
        final ProgressListener progressListener) throws IOException, HttpCodeException {
    logger.debug("uploadFile: put to url: " + url);
    MediaType mediaType = MediaType.parse("application/octet-stream");
    RequestBody requestBody = RequestBodyProgress.create(mediaType, file, startOffset, progressListener);
    Request.Builder requestBuilder = buildRequest().removeHeader(Credentials.AUTHORIZATION_HEADER).url(url)
            .put(requestBody);//from   w  ww . ja v  a2  s.  c o m
    if (startOffset > 0) {
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes ").append(startOffset).append("-").append(file.length() - 1).append("/")
                .append(file.length());
        logger.debug(CONTENT_RANGE_HEADER + ": " + contentRange);
        requestBuilder.addHeader(CONTENT_RANGE_HEADER, contentRange.toString());
    }
    Request request = requestBuilder.build();

    Response response = client.newCall(request).execute();

    String statusLine = response.message();
    logger.debug("headUrl: " + statusLine + " for url " + url);

    int code = response.code();

    ResponseBody responseBody = response.body();
    responseBody.close();

    switch (code) {
    case 201:
    case 202:
        logger.debug("uploadFile: file uploaded successfully: " + file);
        break;
    case 404:
        throw new NotFoundException(code, null);
    case 409:
        throw new ConflictException(code, null);
    case 412:
        throw new PreconditionFailedException(code, null);
    case 413:
        throw new FileTooBigException(code, null);
    case 503:
        throw new ServiceUnavailableException(code, null);
    case 507:
        throw new InsufficientStorageException(code, null);
    default:
        throw new HttpCodeException(code);
    }
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

long getUploadedSize(String url, Hash hash) throws IOException {

    Request request = buildRequest().removeHeader(Credentials.AUTHORIZATION_HEADER).url(url).head()
            .addHeader(ETAG_HEADER, hash.getMd5()).addHeader(SHA256_HEADER, hash.getSha256())
            .addHeader(SIZE_HEADER, String.valueOf(hash.getSize())).build();

    Response response = client.newCall(request).execute();

    int code = response.code();
    ResponseBody responseBody = response.body();
    responseBody.close();
    switch (code) {
    case 200://from  w  w  w  . j  a  v  a2  s .c  o  m
        return Long.valueOf(response.header(CONTENT_LENGTH_HEADER, "0"));
    default:
        return 0;
    }
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

private void close(Response response) throws IOException {
    if (response == null) {
        return;/*from   w  w w . ja v a 2 s.com*/
    }
    ResponseBody responseBody = response.body();
    if (responseBody == null) {
        return;
    }

    responseBody.close();
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

private <T> T parseJson(Response response, Class<T> classOfT) throws IOException {
    ResponseBody responseBody = null;
    try {//from ww  w. j ava 2  s  . c o m
        responseBody = response.body();
        Gson gson = new Gson();
        return gson.fromJson(responseBody.charStream(), classOfT);
    } finally {
        if (responseBody != null) {
            responseBody.close();
        }
    }
}

From source file:de.schildbach.wallet.data.DynamicFeeLoader.java

License:Open Source License

private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile,
        final String userAgent) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);/*from w  w w . j av a  2  s.co m*/
    request.header("User-Agent", userAgent);
    if (targetFile.exists())
        request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));

    final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone();
    httpClient.setConnectTimeout(5, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(5, TimeUnit.SECONDS);
    httpClient.setReadTimeout(5, TimeUnit.SECONDS);
    final Call call = httpClient.newCall(request.build());
    try {
        final Response response = call.execute();
        final int status = response.code();
        if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            log.info("Dynamic fees not modified at {}, took {}", url, watch);
        } else if (status == HttpURLConnection.HTTP_OK) {
            final ResponseBody body = response.body();
            final FileOutputStream os = new FileOutputStream(tempFile);
            Io.copy(body.byteStream(), os);
            os.close();
            final Date lastModified = response.headers().getDate("Last-Modified");
            if (lastModified != null)
                tempFile.setLastModified(lastModified.getTime());
            body.close();
            if (!tempFile.renameTo(targetFile))
                throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
            watch.stop();
            log.info("Dynamic fees fetched from {}, took {}", url, watch);
        } else {
            log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("Problem when fetching dynamic fees rates from " + url, x);
    }
}

From source file:feign.okhttp.OkHttpClient.java

License:Apache License

private static feign.Response.Body toBody(final ResponseBody input) {
    if (input == null || input.contentLength() == 0) {
        return null;
    }/*w ww. ja  v  a  2 s  .c  o m*/
    if (input.contentLength() > Integer.MAX_VALUE) {
        throw new UnsupportedOperationException("Length too long " + input.contentLength());
    }
    final Integer length = input.contentLength() != -1 ? (int) input.contentLength() : null;

    return new feign.Response.Body() {

        @Override
        public void close() throws IOException {
            input.close();
        }

        @Override
        public Integer length() {
            return length;
        }

        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public InputStream asInputStream() throws IOException {
            return input.byteStream();
        }

        @Override
        public Reader asReader() throws IOException {
            return input.charStream();
        }
    };
}