Example usage for com.squareup.okhttp MultipartBuilder addFormDataPart

List of usage examples for com.squareup.okhttp MultipartBuilder addFormDataPart

Introduction

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

Prototype

public MultipartBuilder addFormDataPart(String name, String value) 

Source Link

Document

Add a form data part to the body.

Usage

From source file:FunctionalTest.java

License:Apache License

public static void presignedPostPolicy_test() throws Exception {
    println("Test: presignedPostPolicy(PostPolicy policy)");
    String fileName = createFile(3 * MB);
    PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
    policy.setContentRange(1 * MB, 4 * MB);
    Map<String, String> formData = client.presignedPostPolicy(policy);

    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MultipartBuilder.FORM);
    for (Map.Entry<String, String> entry : formData.entrySet()) {
        multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
    }/* w w  w . j  av a2 s  .  c  o  m*/
    multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:alfio.manager.system.MailgunMailer.java

License:Open Source License

private RequestBody prepareBody(Event event, String to, String subject, String text, Optional<String> html,
        Attachment... attachments) throws IOException {

    String from = event.getDisplayName() + " <" + configurationManager
            .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), MAILGUN_FROM)) + ">";

    if (ArrayUtils.isEmpty(attachments)) {
        FormEncodingBuilder builder = new FormEncodingBuilder().add("from", from).add("to", to)
                .add("subject", subject).add("text", text);

        String replyTo = configurationManager.getStringConfigValue(
                Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            builder.add("h:Reply-To", replyTo);
        }/*from  w ww . ja va 2 s .  c  o  m*/
        html.ifPresent((htmlContent) -> builder.add("html", htmlContent));
        return builder.build();

    } else {
        // https://github.com/square/okhttp/blob/parent-2.1.0/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java
        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        multipartBuilder.addFormDataPart("from", from).addFormDataPart("to", to)
                .addFormDataPart("subject", subject).addFormDataPart("text", text);

        html.ifPresent((htmlContent) -> multipartBuilder.addFormDataPart("html", htmlContent));

        for (Attachment attachment : attachments) {
            byte[] data = attachment.getSource();
            multipartBuilder.addFormDataPart("attachment", attachment.getFilename(), RequestBody
                    .create(MediaType.parse(attachment.getContentType()), Arrays.copyOf(data, data.length)));
        }
        return multipartBuilder.build();
    }
}

From source file:cn.finalteam.okhttpfinal.RequestParams.java

License:Apache License

protected RequestBody getRequestBody() {
    RequestBody body = null;/*from w  ww  .ja  v  a  2s .  c o m*/
    if (jsonBody != null) {
        body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody.toJSONString());
    } else if (requestBody != null) {
        body = requestBody;
    } else if (fileParams.size() > 0) {
        boolean hasData = false;
        MultipartBuilder builder = new MultipartBuilder();
        builder.type(MultipartBuilder.FORM);
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
            hasData = true;
        }

        for (ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
            FileWrapper file = entry.getValue();
            if (file != null) {
                hasData = true;
                builder.addFormDataPart(entry.getKey(), file.getFileName(),
                        RequestBody.create(file.getMediaType(), file.getFile()));
            }
        }
        if (hasData) {
            body = builder.build();
        }
    } else {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        boolean hasData = false;
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
            hasData = true;
        }
        if (hasData) {
            body = builder.build();
        }
    }

    return body;
}

From source file:net.qiujuer.common.okhttp.impl.RequestCallBuilder.java

License:Apache License

protected RequestBody createMultipartBody(StrParam[] stringStrParams, IOParam[] IOParams) {
    MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    builder = buildMultipartBody(builder);

    if (stringStrParams != null && stringStrParams.length > 0) {
        for (StrParam strParam : stringStrParams) {
            if (strParam.key != null && strParam.value != null) {
                builder.addFormDataPart(strParam.key, strParam.value);
                log("buildMultiStringParam: key: " + strParam.key + " value: " + strParam.value);
            } else {
                log("buildMultiStringParam: key: " + (strParam.key != null ? strParam.key : "null") + " value: "
                        + (strParam.value != null ? strParam.value : "null"));
            }//from  www .j  av  a2  s  .  c  om
        }
    }

    if (IOParams != null && IOParams.length > 0) {
        for (IOParam param : IOParams) {
            if (param.key != null && param.file != null) {
                String fileName = param.file.getName();
                RequestBody fileBody = RequestBody.create(MediaType.parse(Util.getFileMimeType(fileName)),
                        param.file);
                builder.addFormDataPart(param.key, fileName, fileBody);
                log("buildMultiFileParam: key: " + param.key + " value: " + fileName);
            } else {
                log("buildMultiFileParam: key: " + (param.key != null ? param.key : "null") + " file: "
                        + (param.file != null ? param.file.getName() : "null"));
            }
        }
    }
    return builder.build();
}

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));
    }/*from  w  w  w . j av  a2  s.co  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));
    }// ww  w . j  av  a2 s .co m

    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);
                }
            });
        }
    });
}