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:com.ibm.watson.developer_cloud.visual_insights.v1.VisualInsights.java

License:Open Source License

/**
 * Upload a set of images as a ZIP file for visual insight extraction.
 * //w w  w  .  j  a  v a2  s .co  m
 * <br>
 * Here is the code to get the {@link Summary} of a collection of images:
 * 
 * <pre>
 * VisualInsights service = new VisualInsights();
 * service.setUsernameAndPassword(&quot;&lt;username&gt;&quot;, &quot;&lt;password&gt;&quot;);
 * 
 * File images = new File(&quot;images.zip&quot;);
 * Summary summary = service.getSummary(images);
 * 
 * System.out.println(summary);
 * </pre>
 * 
 * @param imagesFile the images File
 * @return the {@link Summary} of the collection's visual attributes
 */
public Summary getSummary(final File imagesFile) {
    if (imagesFile == null || !imagesFile.exists())
        throw new IllegalArgumentException("imagesFile cannot be null or empty");

    final MediaType mediaType = HttpMediaType.BINARY_FILE;
    final RequestBody body = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addFormDataPart(IMAGES_FILE, imagesFile.getName(), RequestBody.create(mediaType, imagesFile))
            .build();

    final RequestBuilder requestBuilder = RequestBuilder.post(SUMMARY_PATH).withBody(body);

    return executeRequest(requestBuilder.build(), Summary.class);

}

From source file:com.ibm.watson.developer_cloud.visual_recognition.v2.VisualRecognition.java

License:Open Source License

/**
 * Train a new classifier on the uploaded image data. Upload a compressed (.zip) file of images
 * (.jpg, .png, or .gif) with positive examples that show your classifier and another compressed
 * file with negative examples that are similar to but do NOT show your classifier. <br>
 * <br>/* w  ww  .  ja  v  a2  s .  c om*/
 * Here is an example of how to create a classifier with positive and negatives images:
 * 
 * <pre>
 * VisualRecognition service = new VisualRecognition(&quot;2015-12-02&quot;);
 * service.setUsernameAndPassword(&quot;&lt;username&gt;&quot;, &quot;&lt;password&gt;&quot;);
 * 
 * File positiveImages = new File(&quot;positive.zip&quot;); // zip file with at least 10 images
 * File negativeImages = new File(&quot;negative.zip&quot;);
 * 
 * VisualClassifier foo = service.createClassifier(&quot;foo&quot;, positiveImages, negativeImages);
 * System.out.println(foo);
 * </pre>
 * 
 * 
 * @param name the classifier name
 * @param positiveImages A compressed (.zip) file of images which prominently depict the visual
 *        subject for a new classifier. Must contain a minimum of 10 images.
 * @param negativeImages A compressed (.zip) file of images which do not depict the subject for a
 *        new classifier. Must contain a minimum of 10 images.
 * @return the created {@link VisualClassifier}
 * @see VisualClassifier
 */
public VisualClassifier createClassifier(final String name, final File positiveImages,
        final File negativeImages) {
    Validate.isTrue(positiveImages != null && positiveImages.exists(),
            "positiveImages cannot be null or not be found");
    Validate.isTrue(negativeImages != null && negativeImages.exists(),
            "negativeImages cannot be null or not be found");

    Validate.isTrue(name != null && !name.isEmpty(), "name cannot be null or empty");

    // POST body
    RequestBody body = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addFormDataPart(POSITIVE_EXAMPLES, positiveImages.getName(),
                    RequestBody.create(HttpMediaType.BINARY_FILE, positiveImages))
            .addFormDataPart(NEGATIVE_EXAMPLES, negativeImages.getName(),
                    RequestBody.create(HttpMediaType.BINARY_FILE, negativeImages))
            .addFormDataPart(NAME, name).build();

    Request request = RequestBuilder.post(PATH_CLASSIFIERS).withQuery(VERSION, versionDate).withBody(body)
            .build();

    return executeRequest(request, VisualClassifier.class);
}

From source file:com.ichg.service.volley.OkHttpStack.java

License:Open Source License

@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST:
        // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
        }//from w  w  w  .  j a v  a2  s.  co  m
        break;
    case Request.Method.GET:
        builder.get();
        break;
    case Request.Method.DELETE:
        builder.delete(createRequestBody(request));
        break;
    case Request.Method.POST:
        builder.post(createRequestBody(request));
        break;
    case Request.Method.PUT:
        builder.put(createRequestBody(request));
        break;
    case Request.Method.HEAD:
        builder.head();
        break;
    case Request.Method.OPTIONS:
        builder.method("OPTIONS", null);
        break;
    case Request.Method.TRACE:
        builder.method("TRACE", null);
        break;
    case Request.Method.PATCH:
        builder.patch(createRequestBody(request));
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.imaginarycode.minecraft.redisbungee.util.UUIDFetcher.java

License:Open Source License

public Map<String, UUID> call() throws Exception {
    Map<String, UUID> uuidMap = new HashMap<>();
    int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        String body = RedisBungee.getGson()
                .toJson(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
        Request request = new Request.Builder().url(PROFILE_URL).post(RequestBody.create(JSON, body)).build();
        String response = httpClient.newCall(request).execute().body().string();
        Profile[] array = RedisBungee.getGson().fromJson(response, Profile[].class);
        for (Profile profile : array) {
            UUID uuid = UUIDFetcher.getUUID(profile.id);
            uuidMap.put(profile.name, uuid);
        }//from ww  w . j  a  v a2s.co  m
        if (rateLimiting && i != requests - 1) {
            Thread.sleep(100L);
        }
    }
    return uuidMap;
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

@Override
public void doPut(BaseRequest request) {
    MediaType contentType = MediaType.parse(request.getContentType());
    RequestBody requtestBody = RequestBody.create(contentType, request.getBody());

    Builder builder = new Request.Builder().url(request.getRequestUrl()).put(requtestBody);

    sendRequest(request, builder, request.getBody(), "put");
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

@Override
public void doPost(BaseRequest request) {

    MediaType contentType = MediaType.parse(request.getContentType() + ";" + request.getContentTypeCharSet());
    Builder requestBuilder = new Request.Builder().url(request.getRequestUrl());
    RequestBody requestBodyEntity = null;

    if (BaseRequest.CONTENT_TYPE_MULTIPART.equalsIgnoreCase(request.getContentType())) {
        requestBodyEntity = buildParts(request);
    } else {/*from www .ja  v a2  s .c o  m*/
        requestBodyEntity = RequestBody.create(contentType, request.getBody());
    }

    if (requestBodyEntity != null) {
        requestBuilder.post(requestBodyEntity);
    }

    sendRequest(request, requestBuilder, request.getBody(), "post");

}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

private RequestBody buildParts(BaseRequest request) {

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

    for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) {
        if (h.getFileName() == null) {
            if (h.isContentTypeSet()) {
                multipartBuilder.addFormDataPart(h.getPartName(), null,
                        RequestBody.create(MediaType.parse(request.getContentType()), h.getBody()));
            } else {
                multipartBuilder.addFormDataPart(h.getPartName(), h.getBodyAsString());
            }/*from   ww  w  .  jav a 2s.c  om*/
        } else {
            if (h.isContentTypeSet()) {
                multipartBuilder.addFormDataPart(h.getPartName(), h.getFileName(),
                        RequestBody.create(MediaType.parse(request.getContentType()), h.getBody()));
            } else {
                multipartBuilder.addFormDataPart(h.getPartName(), h.getFileName(),
                        RequestBody.create(null, h.getBody()));
            }
        }
    }
    return multipartBuilder.build();
}

From source file:com.joeyfrazee.nifi.reporting.HttpProvenanceReporter.java

License:Apache License

private void post(String json, String url) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = getHttpClient().newCall(request).execute();
    getLogger().info("{} {} {}",
            new Object[] { Integer.valueOf(response.code()), response.message(), response.body().string() });
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

License:Apache License

public void addStringPostParam(String data) {
    MediaType mediaType = MediaType.parse("text/plain");
    requestBuilder.post(RequestBody.create(mediaType, data));
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

License:Apache License

public void addFilePostParam(String path) {
    MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
    requestBuilder.post(RequestBody.create(mediaType, new File(path)));
}