Example usage for com.squareup.okhttp Request body

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

Introduction

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

Prototype

RequestBody body

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

Click Source Link

Usage

From source file:com.cml.rx.android.api.HttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }//from w  ww.java 2  s  . c om

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();

    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        if (hasRequestBody) {
            // Request body headers are only present when installed as a
            // network interceptor. Force
            // them to be included (when available) so there values are
            // known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly
            // logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (!logBody || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    logger.log("");
                    logger.log("Couldn't decode the response body; charset is likely malformed.");
                    logger.log("<-- END HTTP");

                    return response;
                }
            }

            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }

    return response;
}

From source file:com.davidecirillo.dashboard.data.RestService.java

License:Apache License

public void create() {
    final OkHttpClient client = new OkHttpClient();

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();

    if (BuildConfig.DEBUG)
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    else/*w  w  w  . j a  va 2  s. com*/
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);

    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.add(loggingInterceptor);
    interceptors.add(new LoggingInterceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            Request request = original.newBuilder().method(original.method(), original.body()).build();

            return chain.proceed(request);
        }
    });

    client.networkInterceptors().addAll(interceptors);

    retrofit.Retrofit restAdapterLocal = new retrofit.Retrofit.Builder().client(client)
            .baseUrl(AppConfig.http + mLocalUrl).addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    retrofit.Retrofit restAdapterRemote = new retrofit.Retrofit.Builder().client(client)
            .baseUrl(AppConfig.http + mRemoteUrl).addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    mLocalPiApi = restAdapterLocal.create(PIApi.class);

    mRemotePiApi = restAdapterRemote.create(PIApi.class);
}

From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java

License:Apache License

@Test
public void testStore() throws Exception {
    final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
    final String data = "data";
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    Path output = Paths.get("output/file");
    filesystem.writeContentsToPath(data, output);
    final AtomicBoolean hasCalled = new AtomicBoolean(false);
    HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"),
            /* doStore */ true, filesystem, BUCK_EVENT_BUS) {
        @Override// w  ww.  j a v  a  2  s.  co m
        protected Response storeCall(Request request) throws IOException {
            hasCalled.set(true);

            Buffer buf = new Buffer();
            request.body().writeTo(buf);
            byte[] actualData = buf.readByteArray();

            byte[] expectedData;
            try (ByteArrayOutputStream out = new ByteArrayOutputStream();
                    DataOutputStream dataOut = new DataOutputStream(out)) {
                dataOut.write(HttpArtifactCacheBinaryProtocol.createKeysHeader(ImmutableSet.of(ruleKey)));
                byte[] metadata = HttpArtifactCacheBinaryProtocol.createMetadataHeader(ImmutableSet.of(ruleKey),
                        ImmutableMap.<String, String>of(), ByteSource.wrap(data.getBytes(Charsets.UTF_8)));
                dataOut.writeInt(metadata.length);
                dataOut.write(metadata);
                dataOut.write(data.getBytes(Charsets.UTF_8));
                expectedData = out.toByteArray();
            }

            assertArrayEquals(expectedData, actualData);

            return new Response.Builder().code(HttpURLConnection.HTTP_ACCEPTED).protocol(Protocol.HTTP_1_1)
                    .request(request).build();
        }
    };
    cache.storeImpl(ImmutableSet.of(ruleKey), ImmutableMap.<String, String>of(), output,
            createFinishedEventBuilder());
    assertTrue(hasCalled.get());
    cache.close();
}

From source file:com.facebook.buck.artifact_cache.HttpArtifactCacheTest.java

License:Apache License

@Test
public void testStoreMultipleKeys() throws Exception {
    final RuleKey ruleKey1 = new RuleKey("00000000000000000000000000000000");
    final RuleKey ruleKey2 = new RuleKey("11111111111111111111111111111111");
    final String data = "data";
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    Path output = Paths.get("output/file");
    filesystem.writeContentsToPath(data, output);
    final Set<RuleKey> stored = Sets.newHashSet();
    HttpArtifactCache cache = new HttpArtifactCache("http", null, null, new URI("http://localhost:8080"),
            /* doStore */ true, filesystem, BUCK_EVENT_BUS) {
        @Override//from  w w w  .  j  av a2  s  .c om
        protected Response storeCall(Request request) throws IOException {
            Buffer buf = new Buffer();
            request.body().writeTo(buf);
            try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(buf.readByteArray()))) {
                int keys = in.readInt();
                for (int i = 0; i < keys; i++) {
                    stored.add(new RuleKey(in.readUTF()));
                }
            }
            return new Response.Builder().code(HttpURLConnection.HTTP_ACCEPTED).protocol(Protocol.HTTP_1_1)
                    .request(request).build();
        }
    };
    cache.storeImpl(ImmutableSet.of(ruleKey1, ruleKey2), ImmutableMap.<String, String>of(), output,
            createFinishedEventBuilder());
    assertThat(stored, Matchers.containsInAnyOrder(ruleKey1, ruleKey2));
    cache.close();
}

From source file:com.facebook.buck.rules.HttpArtifactCacheTest.java

License:Apache License

@Test
public void testStore() throws Exception {
    final String data = "data";
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    File output = new File("output/file");
    filesystem.writeContentsToPath(data, output.toPath());
    final AtomicBoolean hasCalled = new AtomicBoolean(false);
    HttpArtifactCache cache = new HttpArtifactCache(null, null, new URL("http://localhost:8080"),
            /* doStore */ true, filesystem, HASH_FUNCTION) {
        @Override/*from w  w  w  . j ava 2  s.  c om*/
        protected Response storeCall(Request request) throws IOException {
            hasCalled.set(true);
            Buffer buf = new Buffer();
            request.body().writeTo(buf);
            assertArrayEquals(createArtifact(data), buf.readByteArray());
            return new Response.Builder().code(HttpURLConnection.HTTP_ACCEPTED).protocol(Protocol.HTTP_1_1)
                    .request(request).build();
        }
    };
    cache.store(new RuleKey("00000000000000000000000000000000"), output);
    assertTrue(hasCalled.get());
    cache.close();
}

From source file:com.facebook.buck.slb.LoadBalancedService.java

License:Apache License

@Override
public Response makeRequest(String path, Request.Builder requestBuilder) throws IOException {
    URI server = slb.getBestServer();
    LoadBalancedServiceEventData.Builder data = LoadBalancedServiceEventData.builder().setServer(server);
    requestBuilder.url(SingleUriService.getFullUrl(server, path));
    Request request = requestBuilder.build();
    if (request.body() != null && request.body().contentLength() != -1) {
        data.setRequestSizeBytes(request.body().contentLength());
    }/*from w ww  .  j  a  v a 2 s.  co  m*/
    Call call = client.newCall(request);
    try {
        Response response = call.execute();
        if (response.body() != null && response.body().contentLength() != -1) {
            data.setResponseSizeBytes(response.body().contentLength());
        }
        slb.reportRequestSuccess(server);
        return response;
    } catch (IOException e) {
        data.setException(e);
        slb.reportRequestException(server);
        throw new IOException(e);
    } finally {
        eventBus.post(new LoadBalancedServiceEvent(data.build()));
    }
}

From source file:com.facebook.buck.slb.ThriftOverHttpServiceTest.java

License:Apache License

@Test
public void testSendValidMessageAndReturnError() throws IOException {
    // TODO(ruibm): Add jetty end to end integration tests for this API.
    FrontendRequest request = new FrontendRequest();
    request.setType(FrontendRequestType.BUILD_STATUS);

    FrontendResponse response = new FrontendResponse();
    response.setType(FrontendRequestType.START_BUILD);

    Capture<Request.Builder> requestBuilder = EasyMock.newCapture();
    HttpResponse httpResponse = EasyMock.createMock(HttpResponse.class);
    EasyMock.expect(httpResponse.code()).andReturn(404).atLeastOnce();
    EasyMock.expect(httpResponse.requestUrl()).andReturn("super url").atLeastOnce();
    EasyMock.expect(httpService.makeRequest(EasyMock.eq("/thrift"), EasyMock.capture(requestBuilder)))
            .andReturn(httpResponse).times(1);

    EasyMock.replay(httpResponse, httpService);
    try {/*from   ww  w.  j  a  v a 2s.c o m*/
        service.makeRequest(request, response);
        Assert.fail("This should've thrown an IOException.");
    } catch (IOException e) {
        Assert.assertNotNull(e);
    }

    Request actualHttpRequest = requestBuilder.getValue().url("http://localhost").build();
    Assert.assertEquals(ThriftOverHttpService.THRIFT_CONTENT_TYPE, actualHttpRequest.body().contentType());

    EasyMock.verify(httpResponse, httpService);
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

public void send(final Request request, final RequestListener listener) {
    c.newCall(buildReq(request)).enqueue(new Callback() {
        @Override//  w  ww .ja  v  a  2 s . c om
        public void onFailure(com.squareup.okhttp.Request r, IOException e) {
            try {
                listener.onFailure(request, e);
            } catch (Throwable t) {
                LOG.warn("Error invoking listener", t);
            }
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response r) throws IOException {
            try {
                if (r != null) {
                    listener.onResponse(new Response(r));
                } else {
                    listener.onFailure(request,
                            new IOException("response is null, review internal okhttp framework."));
                }
            } catch (Throwable t) {
                LOG.warn("Error invoking listener", t);
            } finally {
                IOUtils.closeQuietly(r.body());
            }
        }
    });
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

private RequestBody buildReqBody(Request request) {
    if (request.mime() != null && request.body() != null) {
        return RequestBody.create(MediaType.parse(request.mime()), request.body());
    } else {/*  w w w  .j a  v a  2s .  c  o m*/
        return null;
    }
}

From source file:com.fysl.app.main.LoginActivity.java

License:Open Source License

private void loginInserver(String tel, String password) {

    final ProgressDialog progressDialog = new ProgressDialog(this);

    progressDialog.setMessage("...");
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.show();//ww  w .  j a  va 2 s  .  c  om

    // ???

    RequestBody formBody = new FormEncodingBuilder()

            .add("tel", tel).add("password", MD5Util.getMD5String(password)).build();

    Request request = new Request.Builder().url(Constant.URL_LOGIN).post(formBody).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "?...", Toast.LENGTH_SHORT)
                            .show();
                }

            });
        }

        @Override
        public void onResponse(Response arg0) throws IOException {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    progressDialog.dismiss();

                }

            });
            // System.out.println("response--->" + arg0.body().string());

            if (arg0.isSuccessful()) {
                String result = arg0.body().string();

                System.out.println("result--->" + result);
                final JSONObject json = JSONObject.parseObject(Constant.jsonTokener(result));

                if (json.getInteger("code") == 1000) {

                    final JSONObject userJson = json.getJSONObject("user");
                    DemoApplication.getInstance().savaUserInfo(userJson);
                    // ?
                    // SDK?

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {

                            // TODO Auto-generated method stub
                            loginHuanxin(userJson);
                        }

                    });
                }

            }
        }

    });

}