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:BenchMarkTest.java

License:Open Source License

void doOkHttpRequest() {
    ++okhttp_task_cnt;//from w w  w  .j av a  2  s .  c  o m
    try {
        OkHttpClient client = new OkHttpClient();

        Main.HelloRequest req = new Main.HelloRequest();
        req.user = "okhttp";
        req.text = Integer.toString((int) okhttp_task_cnt);
        //Benchmark 64KB/128KB
        /*req.dumpContent = new byte[64*1024];
        Random rand = new Random();
        rand.nextBytes(req.dumpContent);*/

        final byte[] flatArray = new byte[req.getSerializedSize()];
        final CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(flatArray);
        req.writeTo(output);
        RequestBody reqBody = RequestBody.create(MediaType.parse("application/octet-stream"), flatArray);

        //normal request
        Request request = new Request.Builder().url("http://118.89.24.72:8080/mars/hello2")
                .addHeader("Cache-Control", "no-cache").addHeader("Content-Type", "application/octet-stream")
                .addHeader("Connection", "close").addHeader("Accept", "*/*").post(reqBody).build();

        okhttp_task_time = System.currentTimeMillis();
        // Execute the request and retrieve the response.
        Response response = client.newCall(request).execute();

        ResponseBody body = response.body();
        Main.HelloResponse helloResp = Main.HelloResponse.parseFrom(body.bytes());
        body.close();

        long curr = System.currentTimeMillis();
        okhttp_suc_time += curr - okhttp_task_time;
        ++okhttp_task_suc;
        //Log.i(TAG, "http type:" + type + ", suc cost:" + (curr - okhttp_task_time) + ", count:" + okhttp_task_cnt + ", suc count:" + okhttp_task_suc + ", ctn:" + helloResp.errmsg);
    } catch (Exception e) {
        Log.e(TAG, "http fail cost:" + (System.currentTimeMillis() - okhttp_task_time) + ", count:"
                + okhttp_task_cnt);
    }
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedPutObject_test1() throws Exception {
    println("Test: presignedPutObject(String bucketName, String objectName)");
    String fileName = createFile(3 * MB);
    String urlString = client.presignedPutObject(bucketName, fileName);

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString))
            .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).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();
            }//w  w w. j  av a2  s  .  c om

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

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

From source file:FunctionalTest.java

License:Apache License

public static void presignedPutObject_test2() throws Exception {
    println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
    String fileName = createFile(3 * MB);
    String urlString = client.presignedPutObject(bucketName, fileName, 3600);

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString))
            .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).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();
            }//from w w  w . j  a va  2  s  .  c  o m

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

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

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());
    }/*ww  w  . jav a  2 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:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Serialize the given Java object into request body according to the object's
 * class and the request Content-Type.//from  ww  w.  j a  v a  2 s . c om
 *
 * @param obj The Java object
 * @param contentType The request Content-Type
 * @return The serialized request body
 * @throws ApiException If fail to serialize the given object
 */
public RequestBody serialize(Object obj, String contentType) throws ApiException {
    if (obj instanceof byte[]) {
        // Binary (byte array) body parameter support.
        return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
    } else if (obj instanceof File) {
        // File body parameter support.
        return RequestBody.create(MediaType.parse(contentType), (File) obj);
    } else if (isJsonMime(contentType)) {
        String content;
        if (obj != null) {
            content = json.serialize(obj);
        } else {
            content = null;
        }
        return RequestBody.create(MediaType.parse(contentType), content);
    } else {
        throw new ApiException("Content type \"" + contentType + "\" is not supported");
    }
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Build HTTP call with the given options.
 *
 * @param path The sub-path of the HTTP URL
 * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
 * @param queryParams The query parameters
 * @param body The request body object/*from   w  ww  .  j  av a2  s.  co  m*/
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param authNames The authentications to apply
 * @param progressRequestListener Progress request listener
 * @return The HTTP call
 * @throws ApiException If fail to serialize the request body object
 */
public Call buildCall(String path, String method, List<Pair> queryParams, Object body,
        Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames,
        ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    updateParamsForAuth(authNames, queryParams, headerParams);

    final String url = buildUrl(path, queryParams);
    final Request.Builder reqBuilder = new Request.Builder().url(url);
    processHeaderParams(headerParams, reqBuilder);

    String contentType = (String) headerParams.get("Content-Type");
    // ensuring a default content type
    if (contentType == null) {
        contentType = "application/json";
    }

    RequestBody reqBody;
    if (!HttpMethod.permitsRequestBody(method)) {
        reqBody = null;
    } else if ("application/x-www-form-urlencoded".equals(contentType)) {
        reqBody = buildRequestBodyFormEncoding(formParams);
    } else if ("multipart/form-data".equals(contentType)) {
        reqBody = buildRequestBodyMultipart(formParams);
    } else if (body == null) {
        if ("DELETE".equals(method)) {
            // allow calling DELETE without sending a request body
            reqBody = null;
        } else {
            // use an empty request body (for POST, PUT and PATCH)
            reqBody = RequestBody.create(MediaType.parse(contentType), "");
        }
    } else {
        reqBody = serialize(body, contentType);
    }

    Request request = null;

    if (progressRequestListener != null && reqBody != null) {
        ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
        request = reqBuilder.method(method, progressRequestBody).build();
    } else {
        request = reqBuilder.method(method, reqBody).build();
    }

    return httpClient.newCall(request);
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Build a multipart (file uploading) request body with the given form parameters,
 * which could contain text fields and file fields.
 *
 * @param formParams Form parameters in the form of Map
 * @return RequestBody//from  w  ww.  ja  v a 2 s .c om
 */
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
    MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    for (Entry<String, Object> param : formParams.entrySet()) {
        if (param.getValue() instanceof File) {
            File file = (File) param.getValue();
            Headers partHeaders = Headers.of("Content-Disposition",
                    "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
            MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
            mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
        } else {
            Headers partHeaders = Headers.of("Content-Disposition",
                    "form-data; name=\"" + param.getKey() + "\"");
            mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
        }
    }
    return mpBuilder.build();
}

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  ww  w  .  ja  va  2s .c  om
        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:alfio.manager.system.MailjetMailer.java

License:Open Source License

@Override
public void send(Event event, String to, String subject, String text, Optional<String> html,
        Attachment... attachment) {//from  w  ww .  j a va2s  .  c o  m
    String apiKeyPublic = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(),
            event.getId(), ConfigurationKeys.MAILJET_APIKEY_PUBLIC));
    String apiKeyPrivate = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(),
            event.getId(), ConfigurationKeys.MAILJET_APIKEY_PRIVATE));

    String fromEmail = configurationManager.getRequiredValue(
            Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_FROM));

    //https://dev.mailjet.com/guides/?shell#sending-with-attached-files
    Map<String, Object> mailPayload = new HashMap<>();

    mailPayload.put("FromEmail", fromEmail);
    mailPayload.put("FromName", event.getDisplayName());
    mailPayload.put("Subject", subject);
    mailPayload.put("Text-part", text);
    html.ifPresent(h -> mailPayload.put("Html-part", h));
    mailPayload.put("Recipients", Collections.singletonList(Collections.singletonMap("Email", to)));

    String replyTo = configurationManager.getStringConfigValue(
            Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAIL_REPLY_TO), "");
    if (StringUtils.isNotBlank(replyTo)) {
        mailPayload.put("Headers", Collections.singletonMap("Reply-To", replyTo));
    }

    if (attachment != null && attachment.length > 0) {
        mailPayload.put("Attachments",
                Arrays.stream(attachment).map(MailjetMailer::fromAttachment).collect(Collectors.toList()));
    }

    try {
        RequestBody body = RequestBody.create(MediaType.parse("application/json"),
                Json.GSON.toJson(mailPayload));
        Request request = new Request.Builder().url("https://api.mailjet.com/v3/send")
                .header("Authorization", Credentials.basic(apiKeyPublic, apiKeyPrivate)).post(body).build();

        Response resp = client.newCall(request).execute();
        if (!resp.isSuccessful()) {
            log.warn("sending email was not successful:" + resp);
        }

    } catch (IOException e) {
        log.warn("error while sending email", e);
    }

}

From source file:alfio.plugin.mailchimp.MailChimpPlugin.java

License:Open Source License

private boolean send(int eventId, String address, String apiKey, String email, CustomerName name,
        String language, String eventKey) {
    Map<String, Object> content = new HashMap<>();
    content.put("email_address", email);
    content.put("status", "subscribed");
    Map<String, String> mergeFields = new HashMap<>();
    mergeFields.put("FNAME", name.isHasFirstAndLastName() ? name.getFirstName() : name.getFullName());
    mergeFields.put(ALFIO_EVENT_KEY, eventKey);
    content.put("merge_fields", mergeFields);
    content.put("language", language);
    Request request = new Request.Builder().url(address)
            .header("Authorization", Credentials.basic("alfio", apiKey))
            .put(RequestBody.create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(content, Map.class)))
            .build();/*from w  ww .  j a v  a  2s .  c om*/
    try {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            pluginDataStorage.registerSuccess(String.format("user %s has been subscribed to list", email),
                    eventId);
            return true;
        }
        String responseBody = response.body().string();
        if (response.code() != 400 || responseBody.contains("\"errors\"")) {
            pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, responseBody),
                    eventId);
            return false;
        } else {
            pluginDataStorage.registerWarning(String.format(FAILURE_MSG, email, name, language, responseBody),
                    eventId);
        }
        return true;
    } catch (IOException e) {
        pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, e.toString()),
                eventId);
        return false;
    }
}