Example usage for com.squareup.okhttp RequestBody RequestBody

List of usage examples for com.squareup.okhttp RequestBody RequestBody

Introduction

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

Prototype

RequestBody

Source Link

Usage

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void reusedSinksGetIndependentTimeoutInstances() throws Exception {
    server.enqueue(new MockResponse());
    server.enqueue(new MockResponse());

    // Call 1: set a deadline on the request body.
    RequestBody requestBody1 = new RequestBody() {
        @Override/*from   ww w  .ja  va2  s  .c o  m*/
        public MediaType contentType() {
            return MediaType.parse("text/plain");
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("abc");
            sink.timeout().deadline(5, TimeUnit.SECONDS);
        }
    };
    Request request1 = new Request.Builder().url(server.getUrl("/")).method("POST", requestBody1).build();
    Response response1 = FiberOkHttpUtil.executeInFiber(client, request1);
    assertEquals(200, response1.code());

    // Call 2: check for the absence of a deadline on the request body.
    RequestBody requestBody2 = new RequestBody() {
        @Override
        public MediaType contentType() {
            return MediaType.parse("text/plain");
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            assertFalse(sink.timeout().hasDeadline());
            sink.writeUtf8("def");
        }
    };
    Request request2 = new Request.Builder().url(server.getUrl("/")).method("POST", requestBody2).build();
    Response response2 = FiberOkHttpUtil.executeInFiber(client, request2);
    assertEquals(200, response2.code());

    // Use sequence numbers to confirm the connection was pooled.
    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(1, server.takeRequest().getSequenceNumber());
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private RequestBody uppercase(final RequestBody original) {
    return new RequestBody() {
        @Override//w  w w.j  a v  a 2 s  .c  o m
        public MediaType contentType() {
            return original.contentType();
        }

        @Override
        public long contentLength() throws IOException {
            return original.contentLength();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Sink uppercase = uppercase(sink);
            BufferedSink bufferedSink = Okio.buffer(uppercase);
            original.writeTo(bufferedSink);
            bufferedSink.emit();
        }
    };
}

From source file:com.anony.okhttp.sample.PostStreaming.java

License:Apache License

public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
        @Override/*from   ww  w .j a v a 2  s. co m*/
        public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers\n");
            sink.writeUtf8("-------\n");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
            }
        }

        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n)
                    return factor(x) + "  " + i;
            }
            return Integer.toString(n);
        }
    };

    Request request = new Request.Builder().url("https://api.github.com/markdown/raw").post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java

License:Apache License

protected RequestBody generateRequestBody(final HttpRequest request, final Payload payload) {
    checkNotNull(payload.getContentMetadata().getContentType(), "payload.getContentType");
    return new RequestBody() {
        @Override//from w  w  w  .  j a  va2 s.c o m
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = Okio.source(payload.openStream());
            try {
                sink.writeAll(source);
            } catch (IOException ex) {
                logger.error(ex, "error writing bytes to %s", request.getEndpoint());
                throw ex;
            } finally {
                source.close();
            }
        }

        @Override
        public MediaType contentType() {
            return MediaType.parse(payload.getContentMetadata().getContentType());
        }
    };
}

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

License:Apache License

protected void storeImpl(ImmutableSet<RuleKey> ruleKeys, final ImmutableMap<String, String> metadata,
        final Path file, final Finished.Builder eventBuilder) throws IOException {
    // Build the request, hitting the multi-key endpoint.
    Request.Builder builder = new Request.Builder();
    builder.url(uri.resolve("/artifacts/key").toURL());

    final HttpArtifactCacheBinaryProtocol.StoreRequest storeRequest = new HttpArtifactCacheBinaryProtocol.StoreRequest(
            ruleKeys, metadata, new ByteSource() {
                @Override/*  w  w  w . ja  va 2  s .  c  o m*/
                public InputStream openStream() throws IOException {
                    return projectFilesystem.newFileInputStream(file);
                }
            });

    eventBuilder.setRequestSizeBytes(storeRequest.getContentLength());

    // Wrap the file into a `RequestBody` which uses `ProjectFilesystem`.
    builder.put(new RequestBody() {
        @Override
        public MediaType contentType() {
            return OCTET_STREAM;
        }

        @Override
        public long contentLength() throws IOException {
            return storeRequest.getContentLength();
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
            StoreWriteResult writeResult = storeRequest.write(bufferedSink.outputStream());
            eventBuilder.setArtifactSizeBytes(writeResult.getArtifactSizeBytes());
            eventBuilder.setArtifactContentHash(writeResult.getArtifactContentHashCode().toString());
        }
    });

    // Dispatch the store operation and verify it succeeded.
    Request request = builder.build();
    Response response = storeCall(request);
    final boolean requestFailed = response.code() != HttpURLConnection.HTTP_ACCEPTED;
    if (requestFailed) {
        reportFailure("store(%s, %s): unexpected response: %d", uri, ruleKeys, response.code());
    }

    eventBuilder.setWasUploadSuccessful(!requestFailed);
}

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

License:Apache License

public void storeImpl(RuleKey ruleKey, final File file) throws IOException {
    Request request = createRequestBuilder(ruleKey.toString()).put(new RequestBody() {
        @Override// w ww. j a  v a  2s .c  o m
        public MediaType contentType() {
            return OCTET_STREAM;
        }

        @Override
        public long contentLength() throws IOException {
            return Long.SIZE / Byte.SIZE + projectFilesystem.getFileSize(file.toPath())
                    + hashFunction.bits() / Byte.SIZE;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            try (DataOutputStream output = new DataOutputStream(sink.outputStream());
                    InputStream input = projectFilesystem.newFileInputStream(file.toPath());
                    HashingInputStream hasher = new HashingInputStream(hashFunction, input)) {
                output.writeLong(projectFilesystem.getFileSize(file.toPath()));
                ByteStreams.copy(hasher, output);
                output.write(hasher.hash().asBytes());
            }
        }
    }).build();

    Response response = storeCall(request);

    if (response.code() != HttpURLConnection.HTTP_ACCEPTED) {
        LOGGER.warn("store(%s): unexpected response: %d", ruleKey, response.code());
    }
}

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

License:Open Source License

/**
 * Creates a RequestBody from a mediaType and inputStream given.
 *///from  ww w.  j a v a2 s .  co  m
public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public long contentLength() {
            try {
                return inputStream.available();
            } catch (IOException e) {
                return 0;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = null;
            try {
                source = Okio.source(inputStream);
                sink.writeAll(source);
            } finally {
                Util.closeQuietly(source);
            }
        }
    };
}

From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java

License:Apache License

protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams,
        HttpRequest request, final HttpResponse response) throws IOException {
    try {/*from  ww  w. ja  va2  s . com*/
        String urlStr = url.toString();

        if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) {
            urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT)
                    + "/odo";
        }

        // setup okhttp to ignore ssl issues
        OkHttpClient okHttpClient = getUnsafeOkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setFollowSslRedirects(false);

        Request.Builder okRequestBuilder = new Request.Builder();

        /*
         * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port
         * by checking it only has a : as part of http://
         */
        if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) {
            int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT);
            urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort);
        }

        okRequestBuilder = okRequestBuilder.url(urlStr);

        // copy request headers
        Enumeration<?> enm = request.getFieldNames();
        boolean isGet = "GET".equals(request.getMethod());
        boolean hasContent = false;
        boolean usedContentLength = false;
        long contentLength = 0;
        while (enm.hasMoreElements()) {
            String hdr = (String) enm.nextElement();

            if (!isGet && HttpFields.__ContentType.equals(hdr)) {
                hasContent = true;
            }
            if (!isGet && HttpFields.__ContentLength.equals(hdr)) {
                contentLength = Long.parseLong(request.getField(hdr));
                usedContentLength = true;
            }

            Enumeration<?> vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) {
                        hasContent = true;
                    }

                    if (!_DontProxyHeaders.containsKey(hdr)) {
                        okRequestBuilder = okRequestBuilder.addHeader(hdr, val);
                        //httpReq.addRequestHeader(hdr, val);
                    }
                }
            }
        }

        if ("GET".equals(request.getMethod())) {
            // don't need to do anything else
        } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod())
                || "DELETE".equals(request.getMethod())) {
            RequestBody okRequestBody = null;
            if (hasContent) {
                final String contentType = request.getContentType();
                final byte[] bytes = IOUtils.toByteArray(request.getInputStream());

                okRequestBody = new RequestBody() {
                    @Override
                    public MediaType contentType() {
                        MediaType.parse(contentType);
                        return null;
                    }

                    @Override
                    public void writeTo(BufferedSink bufferedSink) throws IOException {
                        bufferedSink.write(bytes);
                    }
                };

                // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding
                // since okHTTP will automatically chunk even if the request was not chunked
                // this allows Odo to set the appropriate headers when the server request is made
                if (usedContentLength) {
                    okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE",
                            "content-length:" + contentLength);
                }
            } else {
                okRequestBody = RequestBody.create(null, new byte[0]);
            }

            if ("POST".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.post(okRequestBody);
            } else if ("PUT".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.put(okRequestBody);
            } else if ("DELETE".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.delete(okRequestBody);
            }
        } else if ("OPTIONS".equals(request.getMethod())) {
            // NOT SUPPORTED
        } else if ("HEAD".equals(request.getMethod())) {
            okRequestBuilder = okRequestBuilder.head();
        } else {
            LOG.warn("Unexpected request method %s, giving up", request.getMethod());
            request.setHandled(true);
            return -1;
        }

        Request okRequest = okRequestBuilder.build();
        Response okResponse = okHttpClient.newCall(okRequest).execute();

        // Set status and response message
        response.setStatus(okResponse.code());
        response.setReason(okResponse.message());

        // copy response headers
        for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) {
            String headerName = okResponse.headers().name(headerNum);
            if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) {
                response.addField(headerName, okResponse.headers().value(headerNum));
            }
        }

        // write output to response output stream
        try {
            IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream());
        } catch (Exception e) {
            // ignoring this until we refactor the proxy
            // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to
            // The client still gets all of the data it was expecting
        }

        request.setHandled(true);
        return okResponse.body().contentLength();
    } catch (Exception e) {
        LOG.warn("Caught exception proxying: ", e);
        reportError(e, url, response);
        request.setHandled(true);
        return -1;
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized CFolder createFolder(@NonNull String name, @Nullable CFolder parent)
        throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/*from w  ww .  j  a v a 2 s .  co m*/
    // create parameter as json
    final JSONObject params = new JSONObject();
    try {
        params.put("name", name);
        params.put("parent", new JSONObject().put("id", parent != null ? parent.getId() : getRoot().getId()));
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(params.toString());
        }
    };

    Request request = new Request.Builder().url(API_BASE_URL + "/folders")
            .header("Authorization", String.format("Bearer %s", mAccessToken)).post(body).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful() && response.code() == 201) {
            // new folder created
            return buildFolder(new JSONObject(response.body().string()));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized CFolder renameFolder(@NonNull CFolder folder, String name) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//  www  .  j a va2 s  . co m

    // exit if root or same name
    if (folder.isRoot() || folder.getName().equals(name))
        return folder;

    // create parameter as json
    final JSONObject params = new JSONObject();
    try {
        params.put("name", name);
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(params.toString());
        }
    };

    Request request = new Request.Builder().url(API_BASE_URL + "/folders/" + folder.getId())
            .header("Authorization", String.format("Bearer %s", mAccessToken)).put(body).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            // return folder object
            return buildFolder(new JSONObject(response.body().string()));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}