Example usage for com.squareup.okhttp Response body

List of usage examples for com.squareup.okhttp Response body

Introduction

In this page you can find the example usage for com.squareup.okhttp Response body.

Prototype

ResponseBody body

To view the source code for com.squareup.okhttp Response body.

Click Source Link

Usage

From source file:com.facebook.react.devsupport.DevServerHelper.java

License:Open Source License

public void isPackagerRunning(final PackagerStatusCallback callback) {
    String statusURL = createPacakgerStatusURL(getDebugServerHost());
    Request request = new Request.Builder().url(statusURL).build();

    mClient.newCall(request).enqueue(new Callback() {
        @Override// w w  w  . ja  va  2 s  .  com
        public void onFailure(Request request, IOException e) {
            Log.e(ReactConstants.TAG, "IOException requesting status from packager", e);
            callback.onPackagerStatusFetched(false);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                Log.e(ReactConstants.TAG,
                        "Got non-success http code from packager when requesting status: " + response.code());
                callback.onPackagerStatusFetched(false);
                return;
            }
            ResponseBody body = response.body();
            if (body == null) {
                Log.e(ReactConstants.TAG, "Got null body response from packager when requesting status");
                callback.onPackagerStatusFetched(false);
                return;
            }
            if (!PACKAGER_OK_STATUS.equals(body.string())) {
                Log.e(ReactConstants.TAG,
                        "Got unexpected response from packager when requesting status: " + body.string());
                callback.onPackagerStatusFetched(false);
                return;
            }
            callback.onPackagerStatusFetched(true);
        }
    });
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data,
        final Callback callback) {
    // We need to call the callback to avoid leaking memory on JS even when input for sending
    // request is erroneous or insufficient. For non-http based failures we use code 0, which is
    // interpreted as a transport error.
    // Callback accepts following arguments: responseCode, headersString, responseBody

    Request.Builder requestBuilder = new Request.Builder().url(url);

    if (requestId != 0) {
        requestBuilder.tag(requestId);//  w w w  .  j a  va 2  s .  c o  m
    }

    Headers requestHeaders = extractHeaders(headers, data);
    if (requestHeaders == null) {
        callback.invoke(0, null, "Unrecognized headers format");
        return;
    }
    String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
    String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
    requestBuilder.headers(requestHeaders);

    if (data == null) {
        requestBuilder.method(method, null);
    } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String body = data.getString(REQUEST_BODY_KEY_STRING);
        MediaType contentMediaType = MediaType.parse(contentType);
        if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
            RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
            if (requestBody == null) {
                callback.invoke(0, null, "Failed to gzip request body");
                return;
            }
            requestBuilder.method(method, requestBody);
        } else {
            requestBuilder.method(method, RequestBody.create(contentMediaType, body));
        }
    } else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String uri = data.getString(REQUEST_BODY_KEY_URI);
        InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
        if (fileInputStream == null) {
            callback.invoke(0, null, "Could not retrieve file for uri " + uri);
            return;
        }
        requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
    } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
        if (contentType == null) {
            contentType = "multipart/form-data";
        }
        ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
        MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
        if (multipartBuilder == null) {
            return;
        }
        requestBuilder.method(method, multipartBuilder.build());
    } else {
        // Nothing in data payload, at least nothing we could understand anyway.
        // Ignore and treat it as if it were null.
        requestBuilder.method(method, null);
    }

    mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (mShuttingDown) {
                return;
            }
            // We need to call the callback to avoid leaking memory on JS even when input for
            // sending request is erronous or insufficient. For non-http based failures we use
            // code 0, which is interpreted as a transport error
            callback.invoke(0, null, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (mShuttingDown) {
                return;
            }
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                // The stream has been cancelled or closed, nothing we can do
                callback.invoke(0, null, e.getMessage());
                return;
            }

            WritableMap responseHeaders = Arguments.createMap();
            Headers headers = response.headers();
            for (int i = 0; i < headers.size(); i++) {
                String headerName = headers.name(i);
                // multiple values for the same header
                if (responseHeaders.hasKey(headerName)) {
                    responseHeaders.putString(headerName,
                            responseHeaders.getString(headerName) + ", " + headers.value(i));
                } else {
                    responseHeaders.putString(headerName, headers.value(i));
                }
            }

            callback.invoke(response.code(), responseHeaders, responseBody);
        }
    });
}

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testHappyPath() throws IOException {
    InOrder inOrder = Mockito.inOrder(mMockEventReporter);
    hookAlmostRealRequestWillBeSent(mMockEventReporter);
    ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);

    Uri requestUri = Uri.parse("http://www.facebook.com/nowhere");
    String requestText = "Test input";
    Request request = new Request.Builder().url(requestUri.toString())
            .method("POST", RequestBody.create(MediaType.parse("text/plain"), requestText)).build();
    String originalBodyData = "Success!";
    Response reply = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(200)
            .body(ResponseBody.create(MediaType.parse("text/plain"), originalBodyData)).build();
    Response filteredResponse = mInterceptor.intercept(new SimpleTestChain(request, reply, null));

    inOrder.verify(mMockEventReporter).isEnabled();
    inOrder.verify(mMockEventReporter).requestWillBeSent(any(NetworkEventReporter.InspectorRequest.class));
    inOrder.verify(mMockEventReporter).dataSent(anyString(), eq(requestText.length()),
            eq(requestText.length()));/*ww  w  . j a  va  2s  .  c o m*/
    inOrder.verify(mMockEventReporter)
            .responseHeadersReceived(any(NetworkEventReporter.InspectorResponse.class));

    String filteredResponseString = filteredResponse.body().string();
    String interceptedOutput = capturedOutput.toString();

    inOrder.verify(mMockEventReporter).dataReceived(anyString(), anyInt(), anyInt());
    inOrder.verify(mMockEventReporter).responseReadFinished(anyString());

    assertEquals(originalBodyData, filteredResponseString);
    assertEquals(originalBodyData, interceptedOutput);

    inOrder.verifyNoMoreInteractions();
}

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testWithRequestCompression() throws IOException {
    AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest = hookAlmostRealRequestWillBeSent(
            mMockEventReporter);/*from   w  w  w . j a v  a2  s. c om*/

    MockWebServer server = new MockWebServer();
    server.play();
    server.enqueue(new MockResponse().setBody("Success!"));

    final byte[] decompressed = "Request text".getBytes();
    final byte[] compressed = compress(decompressed);
    assertNotEquals("Bogus test: decompressed and compressed lengths match", compressed.length,
            decompressed.length);

    RequestBody compressedBody = RequestBody.create(MediaType.parse("text/plain"), compress(decompressed));
    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Content-Encoding", "gzip")
            .post(compressedBody).build();
    Response response = mClientWithInterceptor.newCall(request).execute();

    // Force a read to complete the flow.
    response.body().string();

    assertArrayEquals(decompressed, capturedRequest.get().body());
    Mockito.verify(mMockEventReporter).dataSent(anyString(), eq(decompressed.length), eq(compressed.length));

    server.shutdown();
}

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testWithResponseCompression() throws IOException {
    ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);

    byte[] uncompressedData = repeat(".", 1024).getBytes();
    byte[] compressedData = compress(uncompressedData);

    MockWebServer server = new MockWebServer();
    server.play();//from   ww  w . j  a  v a 2  s  .  c  om
    server.enqueue(new MockResponse().setBody(compressedData).addHeader("Content-Encoding: gzip"));

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    Response response = mClientWithInterceptor.newCall(request).execute();

    // Verify that the final output and the caller both saw the uncompressed stream.
    assertArrayEquals(uncompressedData, response.body().bytes());
    assertArrayEquals(uncompressedData, capturedOutput.toByteArray());

    // And verify that the StethoInterceptor was able to see both.
    Mockito.verify(mMockEventReporter).dataReceived(anyString(), eq(compressedData.length),
            eq(uncompressedData.length));

    server.shutdown();
}

From source file:com.facebook.stetho.okhttp.StethoInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = mEventReporter.nextRequestId();

    Request request = chain.request();

    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter.isEnabled()) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request,
                requestBodyHelper);/*w  w  w  .ja  v a  2  s. c o m*/
        mEventReporter.requestWillBeSent(inspectorRequest);
    }

    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }

    if (mEventReporter.isEnabled()) {
        if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
            requestBodyHelper.reportDataSent();
        }

        Connection connection = chain.connection();
        mEventReporter
                .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));

        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }

        responseStream = mEventReporter.interpretResponseStream(requestId,
                contentType != null ? contentType.toString() : null, response.header("Content-Encoding"),
                responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }

    return response;
}

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testWithRequestCompression() throws IOException {
    AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest = hookAlmostRealRequestWillBeSent(
            mMockEventReporter);//from   ww w. j av  a 2 s  .c o m

    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse().setBody("Success!"));

    final byte[] decompressed = "Request text".getBytes();
    final byte[] compressed = compress(decompressed);
    assertNotEquals("Bogus test: decompressed and compressed lengths match", compressed.length,
            decompressed.length);

    RequestBody compressedBody = RequestBody.create(MediaType.parse("text/plain"), compress(decompressed));
    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Content-Encoding", "gzip")
            .post(compressedBody).build();
    Response response = mClientWithInterceptor.newCall(request).execute();

    // Force a read to complete the flow.
    response.body().string();

    assertArrayEquals(decompressed, capturedRequest.get().body());
    Mockito.verify(mMockEventReporter).dataSent(anyString(), eq(decompressed.length), eq(compressed.length));

    server.shutdown();
}

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testWithResponseCompression() throws IOException {
    ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);

    byte[] uncompressedData = repeat(".", 1024).getBytes();
    byte[] compressedData = compress(uncompressedData);

    MockWebServer server = new MockWebServer();
    server.start();//from   w  w w.j a  v a2s  . co  m
    server.enqueue(
            new MockResponse().setBody(new Buffer().write(compressedData)).addHeader("Content-Encoding: gzip"));

    Request request = new Request.Builder().url(server.url("/")).build();
    Response response = mClientWithInterceptor.newCall(request).execute();

    // Verify that the final output and the caller both saw the uncompressed stream.
    assertArrayEquals(uncompressedData, response.body().bytes());
    assertArrayEquals(uncompressedData, capturedOutput.toByteArray());

    // And verify that the StethoInterceptor was able to see both.
    Mockito.verify(mMockEventReporter).dataReceived(anyString(), eq(compressedData.length),
            eq(uncompressedData.length));

    server.shutdown();
}

From source file:com.felkertech.n.cumulustv.activities.MainActivity.java

public void moreClick() {
    String[] actions = new String[] { getString(R.string.settings_browse_plugins),
            getString(R.string.settings_switch_google_drive), getString(R.string.settings_refresh_cloud_local),
            getString(R.string.settings_view_licenses), getString(R.string.settings_reset_channel_data),
            getString(R.string.settings_about)/*,
                                              getString(R.string.about_mlc)*/
    };//from  w  ww .  j  a  v a 2 s .  c o m
    new MaterialDialog.Builder(this).title(R.string.more_actions).items(actions)
            .itemsCallback(new MaterialDialog.ListCallback() {
                @Override
                public void onSelection(MaterialDialog materialDialog, View view, int i,
                        CharSequence charSequence) {
                    switch (i) {
                    case 0:
                        ActivityUtils.browsePlugins(MainActivity.this);
                        break;
                    case 1:
                        ActivityUtils.switchGoogleDrive(MainActivity.this, gapi);
                        break;
                    case 2:
                        ActivityUtils.readDriveData(MainActivity.this, gapi);
                        break;
                    case 3:
                        ActivityUtils.oslClick(MainActivity.this);
                        break;
                    case 4:
                        ActivityUtils.deleteChannelData(MainActivity.this, gapi);
                        break;
                    case 5:
                        ActivityUtils.openAbout(MainActivity.this);
                        break;
                    case 6:
                        new MaterialDialog.Builder(MainActivity.this).title(R.string.about_mlc)
                                .content(R.string.about_mlc_summary).positiveText(R.string.about_mlc_issues)
                                .callback(new MaterialDialog.ButtonCallback() {
                                    @Override
                                    public void onPositive(MaterialDialog dialog) {
                                        super.onPositive(dialog);
                                        Intent gi = new Intent(Intent.ACTION_VIEW);
                                        gi.setData(Uri
                                                .parse("https://bitbucket.org/fleker/mlc-music-live-channels"));
                                        startActivity(gi);
                                    }
                                }).show();
                    case 13:
                        final OkHttpClient client = new OkHttpClient();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Request request = new Request.Builder()
                                        .url("http://felkerdigitalmedia.com/sampletv.xml").build();

                                Response response = null;
                                try {
                                    response = client.newCall(request).execute();
                                    //                                            Log.d(TAG, response.body().string().substring(0,36));
                                    String s = response.body().string();
                                    List<Program> programs = XMLTVParser.parse(s);
                                    /*Log.d(TAG, programs.toString());
                                    Log.d(TAG, "Parsed "+programs.size());
                                    Log.d(TAG, "Program 1: "+ programs.get(0).getTitle());*/
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (XmlPullParserException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                        break;
                    }
                }
            }).show();
}

From source file:com.frostwire.util.http.OKHTTPClient.java

License:Open Source License

@Override
public void save(String url, File file, boolean resume, int timeout, String userAgent, String referrer)
        throws IOException {
    FileOutputStream fos;// w  w w.  j  a v  a2  s  .co m
    long rangeStart;
    canceled = false;
    if (resume && file.exists()) {
        fos = new FileOutputStream(file, true);
        rangeStart = file.length();
    } else {
        fos = new FileOutputStream(file, false);
        rangeStart = -1;
    }

    final OkHttpClient okHttpClient = newOkHttpClient();
    final Request.Builder builder = prepareRequestBuilder(okHttpClient, url, timeout, userAgent, referrer,
            null);
    addRangeHeader(rangeStart, -1, builder);
    final Response response = getSyncResponse(okHttpClient, builder);
    final Headers headers = response.headers();
    onHeaders(headers);
    final InputStream in = response.body().byteStream();

    byte[] b = new byte[4096];
    int n;
    while (!canceled && (n = in.read(b, 0, b.length)) != -1) {
        if (!canceled) {
            fos.write(b, 0, n);
            onData(b, 0, n);
        }
    }
    closeQuietly(fos);
    if (canceled) {
        onCancel();
    } else {
        onComplete();
    }
}