Example usage for com.squareup.okhttp RequestBody create

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

Introduction

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

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

/**
 * Call to DHIS Server/*from  w  w w. j a  v a  2s . c o m*/
 * @param data
 * @param url
 */
static Response executeCall(JSONObject data, String url, String method) throws IOException {
    final String DHIS_URL = url;

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();

    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    Request.Builder builder = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL);

    switch (method) {
    case "POST":
        RequestBody postBody = RequestBody.create(JSON, data.toString());
        builder.post(postBody);
        break;
    case "PUT":
        RequestBody putBody = RequestBody.create(JSON, data.toString());
        builder.put(putBody);
        break;
    case "PATCH":
        RequestBody patchBody = RequestBody.create(JSON, data.toString());
        builder.patch(patchBody);
        break;
    case "GET":
        builder.get();
        break;
    }

    Request request = builder.build();
    return client.newCall(request).execute();
}

From source file:org.floens.chan.core.http.ReplyHttpCall.java

License:Open Source License

@Override
public void setup(Request.Builder requestBuilder) {
    boolean thread = reply.resto >= 0;

    password = Long.toHexString(RANDOM.nextLong());

    MultipartBuilder formBuilder = new MultipartBuilder();
    formBuilder.type(MultipartBuilder.FORM);

    formBuilder.addFormDataPart("mode", "regist");
    formBuilder.addFormDataPart("pwd", password);

    if (thread) {
        formBuilder.addFormDataPart("resto", String.valueOf(reply.resto));
    }/*w  ww.ja v a 2 s  . c o  m*/

    formBuilder.addFormDataPart("name", reply.name);
    formBuilder.addFormDataPart("email", reply.options);

    if (!thread && !TextUtils.isEmpty(reply.subject)) {
        formBuilder.addFormDataPart("sub", reply.subject);
    }

    formBuilder.addFormDataPart("com", reply.comment);

    if (reply.captchaResponse != null) {
        if (reply.captchaChallenge != null) {
            formBuilder.addFormDataPart("recaptcha_challenge_field", reply.captchaChallenge);
            formBuilder.addFormDataPart("recaptcha_response_field", reply.captchaResponse);
        } else {
            formBuilder.addFormDataPart("g-recaptcha-response", reply.captchaResponse);
        }
    }

    if (reply.file != null) {
        formBuilder.addFormDataPart("upfile", reply.fileName,
                RequestBody.create(MediaType.parse("application/octet-stream"), reply.file));
    }

    if (reply.spoilerImage) {
        formBuilder.addFormDataPart("spoiler", "on");
    }

    requestBuilder.url(ChanUrls.getReplyUrl(reply.board));
    requestBuilder.post(formBuilder.build());

    if (reply.usePass) {
        requestBuilder.addHeader("Cookie", "pass_id=" + reply.passId);
    }
}

From source file:org.floens.chan.core.manager.ReplyManager.java

License:Open Source License

private void postReplyInternal(final Reply reply, final ReplyListener replyListener, String captchaHash) {
    reply.password = Long.toHexString(random.nextLong());

    MultipartBuilder formBuilder = new MultipartBuilder();
    formBuilder.type(MultipartBuilder.FORM);

    formBuilder.addFormDataPart("mode", "regist");
    formBuilder.addFormDataPart("pwd", reply.password);

    if (reply.resto >= 0) {
        formBuilder.addFormDataPart("resto", String.valueOf(reply.resto));
    }/*from ww w  . j av a 2s . com*/

    formBuilder.addFormDataPart("name", reply.name);
    formBuilder.addFormDataPart("email", reply.email);

    if (!TextUtils.isEmpty(reply.subject)) {
        formBuilder.addFormDataPart("sub", reply.subject);
    }

    formBuilder.addFormDataPart("com", reply.comment);

    if (captchaHash != null) {
        formBuilder.addFormDataPart("g-recaptcha-response", captchaHash);
    }

    if (reply.file != null) {
        formBuilder.addFormDataPart("upfile", reply.fileName,
                RequestBody.create(MediaType.parse("application/octet-stream"), reply.file));
    }

    if (reply.spoilerImage) {
        formBuilder.addFormDataPart("spoiler", "on");
    }

    Request.Builder request = new Request.Builder().url(ChanUrls.getReplyUrl(reply.board))
            .post(formBuilder.build());

    if (reply.usePass) {
        request.addHeader("Cookie", "pass_id=" + reply.passId);
    }

    makeOkHttpCall(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            final ReplyResponse res = new ReplyResponse();
            res.isNetworkError = true;

            runUI(new Runnable() {
                public void run() {
                    replyListener.onResponse(res);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            final ReplyResponse res = new ReplyResponse();
            if (response.isSuccessful()) {
                onReplyPosted(response.body().string(), reply, res);
                response.body().close();
            } else {
                res.isNetworkError = true;
            }

            runUI(new Runnable() {
                public void run() {
                    replyListener.onResponse(res);
                }
            });
        }
    });
}

From source file:org.fs.ghanaian.soap.SoapObjectCallback.java

License:Apache License

/***
 *
 * @param request/*  ww w  .  j a v a  2  s.  c om*/
 * @return
 */
@Override
public CoreCallback<Document> addRequest(Request request) {
    if (request != null) {
        Serializer serializer = new Serializer();
        RequestBody body = RequestBody.create(MediaType.parse("text/xml; charset=utf-8"),
                serializer.serialize(envelope));
        Request newRequest = request.newBuilder().post(body).build();
        mRequest = newRequest;
    }
    return this;
}

From source file:org.fs.ghanaian.util.RequestUtility.java

License:Apache License

/***
 * Converts rawRequestString and Mime to RequestBody object.
 * dont forget to pass charset as charset=utf-8
 *
 * @param rawPost//w  w w. j a  v a2 s.c  om
 * @param mime
 * @return
 */
static RequestBody body(String rawPost, String mime) {
    return RequestBody.create(MediaType.parse(mime), rawPost);
}

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.// www  .  j  a v a2  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
 *//*from  w  w w .j a v a2s . c  om*/
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.fuse.hawkular.agent.monitor.storage.HttpClientBuilder.java

License:Apache License

public Request buildJsonPostRequest(String url, Map<String, String> headers, String jsonPayload) {
    // make sure we are authenticated. see http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder().url(url)
            .addHeader("Authorization", "Basic " + base64Credentials).addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }//w ww.  j a  v a 2 s .com
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

    return requestBuilder.post(body).build();
}

From source file:org.fuse.hawkular.agent.monitor.storage.HttpClientBuilder.java

License:Apache License

public Request buildJsonPutRequest(String url, Map<String, String> headers, String jsonPayload) {
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder().url(url)
            .addHeader("Authorization", "Basic " + base64Credentials).addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }/*from ww  w .  j a  v a2s .  c om*/
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

    return requestBuilder.put(body).build();
}

From source file:org.getlantern.firetweet.extension.streaming.util.OkHttpClientImpl.java

License:Open Source License

private RequestBody getRequestBody(HttpParameter[] params) throws IOException {
    if (params == null)
        return null;
    if (!HttpParameter.containsFile(params)) {
        return RequestBody.create(APPLICATION_FORM_URLENCODED, HttpParameter.encodeParameters(params));
    }//www  .  j  a  v  a  2 s. c  om
    final MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    for (final HttpParameter param : params) {
        if (param.isFile()) {
            RequestBody requestBody;
            if (param.hasFileBody()) {
                requestBody = new StreamRequestBody(MediaType.parse(param.getContentType()),
                        param.getFileBody(), true);
            } else {
                requestBody = RequestBody.create(MediaType.parse(param.getContentType()), param.getFile());
            }
            builder.addFormDataPart(param.getName(), param.getFileName(), requestBody);
        } else {
            builder.addFormDataPart(param.getName(), param.getValue());
        }
    }
    return builder.build();
}