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:io.macgyver.plugin.pagerduty.PagerDutyClientImpl.java

License:Apache License

public ObjectNode postEvent(ObjectNode input) {

    try {/* w  w  w  . j a v  a  2s  .  c  om*/
        Request r = new Request.Builder().url(eventsEndpointUrl + "/create_event.json")
                .post(RequestBody.create(MediaType.parse("application/json"), input.toString()))
                .addHeader("Accept", org.springframework.http.MediaType.APPLICATION_JSON_VALUE).build();

        Response response = getEventClient().newCall(r).execute();

        ObjectNode rv = (ObjectNode) mapper.readTree(response.body().string());

        throwExceptionIfNecessary(rv);

        return rv;
    } catch (IOException e) {
        throw new MacGyverException(e);
    }
}

From source file:io.macgyver.test.MockWebServerTest.java

License:Apache License

@Test
public void testIt() throws IOException, InterruptedException {

    // set up mock response
    mockServer.enqueue(/*from  w  ww  .  java2s  .c o m*/
            new MockResponse().setBody("{\"name\":\"Rob\"}").addHeader("Content-type", "application/json"));

    // set up client and request
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(mockServer.getUrl("/test").toString())
            .post(RequestBody.create(MediaType.parse("application/json"), "{}"))
            .header("Authorization", Credentials.basic("scott", "tiger")).build();

    // make the call
    Response response = client.newCall(request).execute();

    // check the response
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.header("content-type")).isEqualTo("application/json");

    // check the response body
    JsonNode n = new ObjectMapper().readTree(response.body().string());
    assertThat(n.path("name").asText()).isEqualTo("Rob");

    // now make sure that the request was as we exepected it to be
    RecordedRequest recordedRequest = mockServer.takeRequest();
    assertThat(recordedRequest.getPath()).isEqualTo("/test");
    assertThat(recordedRequest.getHeader("Authorization")).isEqualTo("Basic c2NvdHQ6dGlnZXI=");

}

From source file:io.morea.handy.android.SendLogTask.java

License:Apache License

private Set<UUID> sendEvents(final List<Event> events) throws Exception {
    final Set<UUID> sentEvents = new HashSet<>();

    if (events.isEmpty()) {
        return sentEvents;
    }/*from   www  .j  av a2 s.c o m*/

    log.log(Level.INFO,
            String.format("Sending %d events to server %s.", events.size(), configuration.getRemoteEndpoint()));

    final Request request = new Request.Builder().url(configuration.getRemoteEndpoint())
            .post(RequestBody.create(MEDIA_TYPE_JSON, gson.toJson(events)))
            .addHeader("User-Agent", Constant.USER_AGENT).build();

    final Response response = client.newCall(request).execute();

    if (!response.isSuccessful()) {
        log.log(Level.SEVERE,
                String.format("Failed to post events to server, response status is %d.", response.code()));
        return sentEvents;
    }

    for (Event e : events) {
        log.log(Level.FINE, String.format("Event %s successfully sent to server.", e.getIdentifier()));
        sentEvents.add(e.getIdentifier());
    }

    return sentEvents;
}

From source file:io.promagent.it.SpringIT.java

License:Apache License

private Request makePostRequest(String firstName, String lastName) {
    return new Request.Builder().url(System.getProperty("deployment.url") + "/people")
            .method("POST",
                    RequestBody.create(MediaType.parse("application/json"),
                            "{  \"firstName\" : \"" + firstName + "\",  \"lastName\" : \"" + lastName + "\" }"))
            .build();/*  w  ww.  jav a2s  . co  m*/
}

From source file:io.scal.secureshare.controller.ArchiveSiteController.java

@Override
public void upload(Account account, HashMap<String, String> valueMap) {
    Timber.d("Upload file: Entering upload");

    String mediaPath = valueMap.get(VALUE_KEY_MEDIA_PATH);
    boolean useTor = (valueMap.get(VALUE_KEY_USE_TOR).equals("true")) ? true : false;
    String fileName = mediaPath.substring(mediaPath.lastIndexOf("/") + 1, mediaPath.length());
    String licenseUrl = valueMap.get(VALUE_KEY_LICENSE_URL);

    // TODO this should make sure we arn't accidentally using one of archive.org's metadata fields by accident
    String title = valueMap.get(VALUE_KEY_TITLE);
    boolean shareTitle = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TITLE).equals("true")) ? true
            : false;/* w ww  .  j a  v a 2 s . co  m*/
    String slug = valueMap.get(VALUE_KEY_SLUG);
    String tags = valueMap.get(VALUE_KEY_TAGS);
    //always want to include these two tags
    tags += "presssecure,storymaker";
    boolean shareTags = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TAGS).equals("true")) ? true
            : false;
    String author = valueMap.get(VALUE_KEY_AUTHOR);
    boolean shareAuthor = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_AUTHOR).equals("true"))
            ? true
            : false;
    String profileUrl = valueMap.get(VALUE_KEY_PROFILE_URL);
    String locationName = valueMap.get(VALUE_KEY_LOCATION_NAME);
    boolean shareLocation = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_LOCATION).equals("true"))
            ? true
            : false;
    String body = valueMap.get(VALUE_KEY_BODY);
    boolean shareDescription = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_DESCRIPTION)
            .equals("true")) ? true : false;

    File file = new File(mediaPath);
    if (!file.exists()) {
        jobFailed(null, 4000473, "Internet Archive upload failed: invalid file");
        return;
    }

    String mediaType = Util.getMediaType(mediaPath);

    OkHttpClient client = new OkHttpClient();

    if (super.torCheck(useTor, super.mContext)) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ORBOT_HOST, ORBOT_HTTP_PORT));
        client.setProxy(proxy);
    }

    // FIXME we are putting a random 4 char string in the bucket name for collision avoidance, we might want to do this differently?
    String urlPath = null;
    String url = null;
    if (shareTitle) {
        String randomString = new Util.RandomString(4).nextString();
        urlPath = slug + "-" + randomString;
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    } else {
        urlPath = new Util.RandomString(16).nextString(); // FIXME need to use real GUIDs
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    }
    Timber.d("uploading to url: " + url);

    Request.Builder builder = new Request.Builder().url(url).put(RequestBody.create(MEDIA_TYPE, file))
            .addHeader("Accept", "*/*").addHeader("x-amz-auto-make-bucket", "1")
            //                .addHeader("x-archive-meta-collection", "storymaker")
            //            .addHeader("x-archive-meta-sponsor", "Sponsor 998")
            .addHeader("x-archive-meta-language", "eng") // FIXME pull meta language from story
            .addHeader("authorization", "LOW " + account.getUserName() + ":" + account.getCredentials());

    if (shareAuthor && author != null) {
        builder.addHeader("x-archive-meta-author", author);
        if (profileUrl != null) {
            builder.addHeader("x-archive-meta-authorurl", profileUrl);
        }
    }

    if (mediaType != null) {
        builder.addHeader("x-archive-meta-mediatype", mediaType);
        if (mediaType.contains("audio")) {
            builder.addHeader("x-archive-meta-collection", "opensource_audio");
        } else {
            builder.addHeader("x-archive-meta-collection", "opensource_movies");
        }
    } else {
        builder.addHeader("x-archive-meta-collection", "opensource_movies");
    }

    if (shareLocation && locationName != null) {
        builder.addHeader("x-archive-meta-location", locationName);
    }

    if (shareTags && tags != null) {
        String keywords = tags.replace(',', ';').replaceAll(" ", "");
        builder.addHeader("x-archive-meta-subject", keywords);
    }

    if (shareDescription && body != null) {
        builder.addHeader("x-archive-meta-description", body);
    }

    if (shareTitle && title != null) {
        builder.addHeader("x-archive-meta-title", title);
    }

    if (licenseUrl != null) {
        builder.addHeader("x-archive-meta-licenseurl", licenseUrl);
    }

    Request request = builder.build();

    UploadFileTask uploadFileTask = new UploadFileTask(client, request);
    uploadFileTask.execute();
}

From source file:io.scal.secureshareui.controller.ArchiveSiteController.java

@Override
public void upload(Account account, HashMap<String, String> valueMap) {
    Log.d(TAG, "Upload file: Entering upload");

    String mediaPath = valueMap.get(VALUE_KEY_MEDIA_PATH);
    boolean useTor = (valueMap.get(VALUE_KEY_USE_TOR).equals("true")) ? true : false;
    String fileName = mediaPath.substring(mediaPath.lastIndexOf("/") + 1, mediaPath.length());
    String licenseUrl = valueMap.get(VALUE_KEY_LICENSE_URL);

    // TODO this should make sure we arn't accidentally using one of archive.org's metadata fields by accident
    String title = valueMap.get(VALUE_KEY_TITLE);
    boolean shareTitle = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TITLE).equals("true")) ? true
            : false;//from w w w. j ava 2  s. c  o  m
    String slug = valueMap.get(VALUE_KEY_SLUG);
    String tags = valueMap.get(VALUE_KEY_TAGS);
    //always want to include these two tags
    tags += "presssecure,storymaker";
    boolean shareTags = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TAGS).equals("true")) ? true
            : false;
    String author = valueMap.get(VALUE_KEY_AUTHOR);
    boolean shareAuthor = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_AUTHOR).equals("true"))
            ? true
            : false;
    String profileUrl = valueMap.get(VALUE_KEY_PROFILE_URL);
    String locationName = valueMap.get(VALUE_KEY_LOCATION_NAME);
    boolean shareLocation = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_LOCATION).equals("true"))
            ? true
            : false;
    String body = valueMap.get(VALUE_KEY_BODY);
    boolean shareDescription = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_DESCRIPTION)
            .equals("true")) ? true : false;

    File file = new File(mediaPath);
    if (!file.exists()) {
        jobFailed(null, 4000473, "Internet Archive upload failed: invalid file");
        return;
    }

    String mediaType = Util.getMediaType(mediaPath);

    OkHttpClient client = new OkHttpClient();

    if (super.torCheck(useTor, super.mContext)) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ORBOT_HOST, ORBOT_HTTP_PORT));
        client.setProxy(proxy);
    }

    // FIXME we are putting a random 4 char string in the bucket name for collision avoidance, we might want to do this differently?
    String urlPath = null;
    String url = null;
    if (shareTitle) {
        String randomString = new Util.RandomString(4).nextString();
        urlPath = slug + "-" + randomString;
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    } else {
        urlPath = new Util.RandomString(16).nextString(); // FIXME need to use real GUIDs
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    }
    Log.d(TAG, "uploading to url: " + url);

    Request.Builder builder = new Request.Builder().url(url).put(RequestBody.create(MEDIA_TYPE, file))
            .addHeader("Accept", "*/*").addHeader("x-amz-auto-make-bucket", "1")
            //                .addHeader("x-archive-meta-collection", "storymaker")
            //            .addHeader("x-archive-meta-sponsor", "Sponsor 998")
            .addHeader("x-archive-meta-language", "eng") // FIXME pull meta language from story
            .addHeader("authorization", "LOW " + account.getUserName() + ":" + account.getCredentials());

    if (shareAuthor && author != null) {
        builder.addHeader("x-archive-meta-author", author);
        if (profileUrl != null) {
            builder.addHeader("x-archive-meta-authorurl", profileUrl);
        }
    }

    if (mediaType != null) {
        builder.addHeader("x-archive-meta-mediatype", mediaType);
        if (mediaType.contains("audio")) {
            builder.addHeader("x-archive-meta-collection", "opensource_audio");
        } else {
            builder.addHeader("x-archive-meta-collection", "opensource_movies");
        }
    } else {
        builder.addHeader("x-archive-meta-collection", "opensource_movies");
    }

    if (shareLocation && locationName != null) {
        builder.addHeader("x-archive-meta-location", locationName);
    }

    if (shareTags && tags != null) {
        String keywords = tags.replace(',', ';').replaceAll(" ", "");
        builder.addHeader("x-archive-meta-subject", keywords);
    }

    if (shareDescription && body != null) {
        builder.addHeader("x-archive-meta-description", body);
    }

    if (shareTitle && title != null) {
        builder.addHeader("x-archive-meta-title", title);
    }

    if (licenseUrl != null) {
        builder.addHeader("x-archive-meta-licenseurl", licenseUrl);
    }

    Request request = builder.build();

    UploadFileTask uploadFileTask = new UploadFileTask(client, request);
    uploadFileTask.execute();
}

From source file:io.sidecar.client.SidecarDeleteRequest.java

License:Apache License

@Override
public SidecarResponse send() {
    try {//  w  w w.  ja va 2s  .c o  m
        String payloadAsJson = mapper.writeValueAsString(payload);

        LOGGER.debug("Creating sidecar DELETE request... " + url);
        LOGGER.debug("JSON_MEDIA_TYPE payload is {}", payloadAsJson);

        Request.Builder request = new Request.Builder().url(url)
                .delete(RequestBody.create(JSON_MEDIA_TYPE, payloadAsJson));

        // add the required headers for signing the request
        signHeaders("DELETE", url.getPath(), request, payloadAsJson);
        return send(request.build());
    } catch (Exception e) {
        throw propagate(e);
    }
}

From source file:io.sidecar.client.SidecarPostRequest.java

License:Apache License

@Override
public SidecarResponse send() {
    try {//from  w  w  w .  j  a  va  2  s.  c om
        String payloadAsJson = mapper.writeValueAsString(payload);

        LOGGER.debug("Creating sidecar POST request... " + url);
        LOGGER.debug("JSON_MEDIA_TYPE payload is {}", payloadAsJson);

        Request.Builder request = new Request.Builder().url(url)
                .post(RequestBody.create(JSON_MEDIA_TYPE, payloadAsJson));

        // add the required headers for signing the request
        signHeaders("POST", url.getPath(), request, payloadAsJson);
        return send(request.build());
    } catch (Exception e) {
        throw propagate(e);
    }
}

From source file:io.sidecar.client.SidecarPutRequest.java

License:Apache License

@Override
public SidecarResponse send() {
    try {//from  ww  w  .  j a  v  a 2 s .co  m
        String payloadAsJson = mapper.writeValueAsString(event);

        LOGGER.debug("Creating sidecar PUT request... " + url);
        LOGGER.debug("JSON_MEDIA_TYPE payload is {}", payloadAsJson);

        Request.Builder request = new Request.Builder().url(url)
                .put(RequestBody.create(JSON_MEDIA_TYPE, payloadAsJson));

        // add the required headers for signing the request
        signHeaders("PUT", url.getPath(), request, payloadAsJson);

        return send(request.build());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:it.smartcommunitylab.ApiClient.java

License:Apache License

/**
 * Build an HTTP request 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 collectionQueryParams The collection query parameters
 * @param body The request body object/*  w w w  . jav  a 2s  .  c om*/
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param authNames The authentications to apply
 * @param progressRequestListener Progress request listener
 * @return The HTTP request 
 * @throws ApiException If fail to serialize the request body object
 */
public Request buildRequest(String path, String method, List<Pair> queryParams,
        List<Pair> collectionQueryParams, 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, collectionQueryParams);
    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 request;
}