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:io.minio.MinioClient.java

License:Apache License

/**
 * Creates Request object for given request parameters.
 *
 * @param method         HTTP method.//from   www .  ja v a  2  s.c  om
 * @param bucketName     Bucket name.
 * @param objectName     Object name in the bucket.
 * @param region         Amazon S3 region of the bucket.
 * @param headerMap      Map of HTTP headers for the request.
 * @param queryParamMap  Map of HTTP query parameters of the request.
 * @param contentType    Content type of the request body.
 * @param body           HTTP request body.
 * @param length         Length of HTTP request body.
 */
private Request createRequest(Method method, String bucketName, String objectName, String region,
        Map<String, String> headerMap, Map<String, String> queryParamMap, final String contentType,
        final Object body, final int length)
        throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException {
    if (bucketName == null && objectName != null) {
        throw new InvalidBucketNameException(NULL_STRING, "null bucket name for object '" + objectName + "'");
    }

    HttpUrl.Builder urlBuilder = this.baseUrl.newBuilder();

    if (bucketName != null) {
        checkBucketName(bucketName);

        String host = this.baseUrl.host();
        if (host.equals(S3_AMAZONAWS_COM)) {
            // special case: handle s3.amazonaws.com separately
            if (region != null) {
                host = AwsS3Endpoints.INSTANCE.endpoint(region);
            }

            boolean usePathStyle = false;
            if (method == Method.PUT && objectName == null && queryParamMap == null) {
                // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com
                usePathStyle = true;
            } else if (queryParamMap != null && queryParamMap.containsKey("location")) {
                // use path style for location query
                usePathStyle = true;
            } else if (bucketName.contains(".") && this.baseUrl.isHttps()) {
                // use path style where '.' in bucketName causes SSL certificate validation error
                usePathStyle = true;
            }

            if (usePathStyle) {
                urlBuilder.host(host);
                urlBuilder.addPathSegment(bucketName);
            } else {
                urlBuilder.host(bucketName + "." + host);
            }
        } else {
            urlBuilder.addPathSegment(bucketName);
        }
    }

    if (objectName != null) {
        for (String pathSegment : objectName.split("/")) {
            // Limitation:
            // 1. OkHttp does not allow to add '.' and '..' as path segment.
            // 2. Its not allowed to add path segment as '/', '//', '/usr' or 'usr/'.
            urlBuilder.addPathSegment(pathSegment);
        }
    }

    if (queryParamMap != null) {
        for (Map.Entry<String, String> entry : queryParamMap.entrySet()) {
            urlBuilder.addEncodedQueryParameter(Signer.encodeQueryString(entry.getKey()),
                    Signer.encodeQueryString(entry.getValue()));
        }
    }

    RequestBody requestBody = null;
    if (body != null) {
        requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                if (contentType != null) {
                    return MediaType.parse(contentType);
                } else {
                    return MediaType.parse("application/octet-stream");
                }
            }

            @Override
            public long contentLength() {
                if (body instanceof InputStream || body instanceof RandomAccessFile || body instanceof byte[]) {
                    return length;
                }

                if (length == 0) {
                    return -1;
                } else {
                    return length;
                }
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                byte[] data = null;

                if (body instanceof InputStream) {
                    InputStream stream = (InputStream) body;
                    sink.write(Okio.source(stream), length);
                } else if (body instanceof RandomAccessFile) {
                    RandomAccessFile file = (RandomAccessFile) body;
                    sink.write(Okio.source(Channels.newInputStream(file.getChannel())), length);
                } else if (body instanceof byte[]) {
                    sink.write(data, 0, length);
                } else {
                    sink.writeUtf8(body.toString());
                }
            }
        };
    }

    HttpUrl url = urlBuilder.build();
    // urlBuilder does not encode some characters properly for Amazon S3.
    // Encode such characters properly here.
    List<String> pathSegments = url.encodedPathSegments();
    urlBuilder = url.newBuilder();
    for (int i = 0; i < pathSegments.size(); i++) {
        urlBuilder.setEncodedPathSegment(i,
                pathSegments.get(i).replaceAll("\\!", "%21").replaceAll("\\$", "%24").replaceAll("\\&", "%26")
                        .replaceAll("\\'", "%27").replaceAll("\\(", "%28").replaceAll("\\)", "%29")
                        .replaceAll("\\*", "%2A").replaceAll("\\+", "%2B").replaceAll("\\,", "%2C")
                        .replaceAll("\\:", "%3A").replaceAll("\\;", "%3B").replaceAll("\\=", "%3D")
                        .replaceAll("\\@", "%40").replaceAll("\\[", "%5B").replaceAll("\\]", "%5D"));
    }
    url = urlBuilder.build();

    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(url);
    requestBuilder.method(method.toString(), requestBody);
    if (headerMap != null) {
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            requestBuilder.header(entry.getKey(), entry.getValue());
        }
    }

    String sha256Hash = null;
    String md5Hash = null;
    if (this.accessKey != null && this.secretKey != null) {
        // No need to compute sha256 if endpoint scheme is HTTPS. Issue #415.
        if (url.isHttps()) {
            sha256Hash = "UNSIGNED-PAYLOAD";
            if (body instanceof BufferedInputStream) {
                md5Hash = Digest.md5Hash((BufferedInputStream) body, length);
            } else if (body instanceof RandomAccessFile) {
                md5Hash = Digest.md5Hash((RandomAccessFile) body, length);
            } else if (body instanceof byte[]) {
                byte[] data = (byte[]) body;
                md5Hash = Digest.md5Hash(data, length);
            }
        } else {
            if (body == null) {
                sha256Hash = Digest.sha256Hash(new byte[0]);
            } else {
                if (body instanceof BufferedInputStream) {
                    String[] hashes = Digest.sha256md5Hashes((BufferedInputStream) body, length);
                    sha256Hash = hashes[0];
                    md5Hash = hashes[1];
                } else if (body instanceof RandomAccessFile) {
                    String[] hashes = Digest.sha256md5Hashes((RandomAccessFile) body, length);
                    sha256Hash = hashes[0];
                    md5Hash = hashes[1];
                } else if (body instanceof byte[]) {
                    byte[] data = (byte[]) body;
                    sha256Hash = Digest.sha256Hash(data, length);
                    md5Hash = Digest.md5Hash(data, length);
                } else {
                    sha256Hash = Digest.sha256Hash(body.toString());
                }
            }
        }
    }

    if (md5Hash != null) {
        requestBuilder.header("Content-MD5", md5Hash);
    }
    if (url.port() == 80 || url.port() == 443) {
        requestBuilder.header("Host", url.host());
    } else {
        requestBuilder.header("Host", url.host() + ":" + url.port());
    }
    requestBuilder.header("User-Agent", this.userAgent);
    if (sha256Hash != null) {
        requestBuilder.header("x-amz-content-sha256", sha256Hash);
    }
    DateTime date = new DateTime();
    requestBuilder.header("x-amz-date", date.toString(DateFormat.AMZ_DATE_FORMAT));

    return requestBuilder.build();
}

From source file:io.takari.aether.okhttp.OkHttpAetherClient.java

License:Open Source License

@Override
// i need the response
public Response put(String uri, final RetryableSource source) throws IOException {
    Response response;//ww  w. j a  v  a  2  s  . co  m
    do {
        // disable response caching
        // connection.addRequestProperty("Cache-Control", "no-cache") may work too
        OkHttpClient httpClient = this.httpClient.clone().setCache(null);

        final MediaType mediaType = MediaType.parse("application/octet-stream");
        final RequestBody body = new RequestBody() {

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                source.copyTo(sink.outputStream());
            }

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

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

        Request.Builder builder = builder(uri, null).put(body);

        if (source.length() > 0) {
            builder.header("Content-Length", String.valueOf(source.length()));
        }

        response = execute(httpClient, builder.build());
    } while (response == null);
    return response;
}

From source file:it.smartcommunitylab.GzipRequestInterceptor.java

License:Apache License

private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);/*from   www.  j  a  v a 2  s .  c  o  m*/
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}

From source file:it.smartcommunitylab.GzipRequestInterceptor.java

License:Apache License

private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
        @Override// www  .  j  av a 2s .co  m
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            return -1; // We don't know the compressed length in advance!
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}

From source file:net.ltgt.resteasy.client.okhttp.OkHttpClientEngine.java

License:Apache License

private RequestBody createRequestBody(final ClientInvocation request) {
    if (request.getEntity() == null) {
        return null;
    }/*from www. j a  v a 2s . c  o  m*/

    // NOTE: this will invoke WriterInterceptors which can possibly change the request,
    // so it must be done first, before reading any header.
    final Buffer buffer = new Buffer();
    try {
        request.writeRequestBody(buffer.outputStream());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    javax.ws.rs.core.MediaType mediaType = request.getHeaders().getMediaType();
    final MediaType contentType = (mediaType == null) ? null : MediaType.parse(mediaType.toString());

    return new RequestBody() {
        @Override
        public long contentLength() throws IOException {
            return buffer.size();
        }

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

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer, buffer.size());
        }
    };
}

From source file:org.apache.nifi.processors.standard.InvokeHTTP.java

License:Apache License

private RequestBody getRequestBodyToSend(final ProcessSession session, final ProcessContext context,
        final FlowFile requestFlowFile) {
    if (context.getProperty(PROP_SEND_BODY).asBoolean()) {
        return new RequestBody() {
            @Override// w ww .j a v a2  s .  c o m
            public MediaType contentType() {
                String contentType = context.getProperty(PROP_CONTENT_TYPE)
                        .evaluateAttributeExpressions(requestFlowFile).getValue();
                contentType = StringUtils.isBlank(contentType) ? DEFAULT_CONTENT_TYPE : contentType;
                return MediaType.parse(contentType);
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                session.exportTo(requestFlowFile, sink.outputStream());
            }

            @Override
            public long contentLength() {
                return useChunked ? -1 : requestFlowFile.getSize();
            }
        };
    } else {
        return RequestBody.create(null, new byte[0]);
    }
}

From source file:org.fuse.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

/**
 * Sends a message to the server asynchronously. This method returns immediately; the message may not go out until
 * some time in the future./*  ww w .  j  a v a  2 s . c o m*/
 *
 * @param messageWithData the message to send
 */
public void sendAsync(final BasicMessageWithExtraData<? extends BasicMessage> messageWithData) {
    if (webSocket == null) {
        throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
    }

    final BasicMessage message = messageWithData.getBasicMessage();
    configurationAuthentication(message);

    sendExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                if (messageWithData.getBinaryData() == null) {
                    String messageString = ApiDeserializer.toHawkularFormat(message);
                    Buffer buffer = new Buffer();
                    buffer.writeUtf8(messageString);
                    RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
                    FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                } else {
                    final BinaryData messageData = ApiDeserializer.toHawkularFormat(message,
                            messageWithData.getBinaryData());

                    RequestBody requestBody = new RequestBody() {
                        @Override
                        public MediaType contentType() {
                            return WebSocket.BINARY;
                        }

                        @Override
                        public void writeTo(BufferedSink bufferedSink) throws IOException {
                            emitToSink(messageData, bufferedSink);
                        }
                    };

                    FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                }
            } catch (Throwable t) {
                log.errorFailedToSendOverFeedComm(message.getClass().getName(), t);
            }
        }
    });
}

From source file:org.fuse.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

/**
 * Sends a message to the server synchronously. This will return only when the message has been sent.
 *
 * @param messageWithData the message to send
 * @throws IOException if the message failed to be sent
 *///  w w w.  java2s  .c o m
public void sendSync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) throws Exception {
    if (webSocket == null) {
        throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
    }

    BasicMessage message = messageWithData.getBasicMessage();
    configurationAuthentication(message);

    if (messageWithData.getBinaryData() == null) {
        String messageString = ApiDeserializer.toHawkularFormat(message);
        Buffer buffer = new Buffer();
        buffer.writeUtf8(messageString);
        RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
        FeedCommProcessor.this.webSocket.sendMessage(requestBody);
    } else {
        final BinaryData messageData = ApiDeserializer.toHawkularFormat(message,
                messageWithData.getBinaryData());

        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return WebSocket.BINARY;
            }

            @Override
            public void writeTo(BufferedSink bufferedSink) throws IOException {
                emitToSink(messageData, bufferedSink);
            }
        };

        FeedCommProcessor.this.webSocket.sendMessage(requestBody);

    }
}

From source file:org.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

/**
 * Sends a message to the server asynchronously. This method returns immediately; the message may not go out until
 * some time in the future./*w  w  w  .  j a  v a 2 s.c o  m*/
 *
 * @param messageWithData the message to send
 */
public void sendAsync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) {
    if (webSocket == null) {
        throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
    }

    BasicMessage message = messageWithData.getBasicMessage();
    configurationAuthentication(message);

    sendExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                if (messageWithData.getBinaryData() == null) {
                    String messageString = ApiDeserializer.toHawkularFormat(message);
                    Buffer buffer = new Buffer();
                    buffer.writeUtf8(messageString);
                    RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
                    FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                } else {
                    BinaryData messageData = ApiDeserializer.toHawkularFormat(message,
                            messageWithData.getBinaryData());

                    RequestBody requestBody = new RequestBody() {
                        @Override
                        public MediaType contentType() {
                            return WebSocket.BINARY;
                        }

                        @Override
                        public void writeTo(BufferedSink bufferedSink) throws IOException {
                            emitToSink(messageData, bufferedSink);
                        }
                    };

                    FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                }
            } catch (Throwable t) {
                log.errorFailedToSendOverFeedComm(message.getClass().getName(), t);
            }
        }
    });
}

From source file:org.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

/**
 * Sends a message to the server synchronously. This will return only when the message has been sent.
 *
 * @param messageWithData the message to send
 * @throws IOException if the message failed to be sent
 *//*w  ww .j  a v  a  2  s.  c  o m*/
public void sendSync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) throws Exception {
    if (webSocket == null) {
        throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
    }

    BasicMessage message = messageWithData.getBasicMessage();
    configurationAuthentication(message);

    if (messageWithData.getBinaryData() == null) {
        String messageString = ApiDeserializer.toHawkularFormat(message);
        Buffer buffer = new Buffer();
        buffer.writeUtf8(messageString);
        RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
        FeedCommProcessor.this.webSocket.sendMessage(requestBody);
    } else {
        BinaryData messageData = ApiDeserializer.toHawkularFormat(message, messageWithData.getBinaryData());

        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return WebSocket.BINARY;
            }

            @Override
            public void writeTo(BufferedSink bufferedSink) throws IOException {
                emitToSink(messageData, bufferedSink);
            }
        };

        FeedCommProcessor.this.webSocket.sendMessage(requestBody);

    }
}