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.hkm.root.Tasks.upload_data.java

License:Open Source License

protected String OCokHttpPostData(final String url, final String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(body).build();
    OkHttpClient use_client = client.clone();
    Response response = use_client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else/*from w ww  . j av a 2  s. c  o  m*/
        throw new IOException("not success on HTTP request.");
}

From source file:com.hkm.root.Tasks.upload_data.java

License:Open Source License

public void OCokHttpUpload(ArrayList<Uri> img_list, final String endpoint, final MediaType typ)
        throws IOException, Exception {
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    MultipartBuilder mb = new MultipartBuilder();
    mb.type(MultipartBuilder.FORM);//from ww  w. j  a  v a 2 s.co  m
    for (Uri i : img_list) {
        final File file_location = i.toString().startsWith("file:")
                ? new File(i.toString().replace("file:///", ""))
                : new File(Tool.getRealPathFromURI(ac, i));
        final RequestBody content_data = RequestBody.create(typ, file_location);
        final String disposition = String.format(Locale.getDefault(), "form-data; name=\"%s\"; filename=\"%s\"",
                "target-" + post_target, file_location.getName());
        final String disposition_alt = String.format(Locale.getDefault(), "file; filename=\"%s\"",
                file_location.getName());
        mb.addPart(Headers.of("Content-Disposition", disposition_alt, "Content-Transfer-Encoding", "binary"),
                content_data);
    }

    RequestBody requestBody = mb.build();
    Request requestBuild = new Request.Builder().url(endpoint + "?pid=" + job_id + "&target=" + post_target)
            .post(requestBody).tag("post_image").build();
    execute_upload(requestBuild);
}

From source file:com.horntell.http.Request.java

private Response doPostRequest(String url, Map<String, Object> params) throws IOException {

    String credential = Credentials.basic(App.getKey(), App.getSecret());
    String json = new JSONObject(params).toString();

    RequestBody body = RequestBody.create(JSON, json);
    com.squareup.okhttp.Request request;
    request = new com.squareup.okhttp.Request.Builder().url(url).header("Authorization", credential)
            .addHeader("Accept", "application/vnd.horntell." + App.getVersion() + "+json")
            .addHeader("Content-Type", "text/json").post(body).build();

    com.squareup.okhttp.Response response = client.newCall(request).execute();

    return new Response(response);
}

From source file:com.horntell.http.Request.java

private Response doPutRequest(String url, Map<String, Object> params) throws IOException {

    String credential = Credentials.basic(App.getKey(), App.getSecret());
    String json = new JSONObject(params).toString();

    RequestBody body = RequestBody.create(JSON, json);
    com.squareup.okhttp.Request request;
    request = new com.squareup.okhttp.Request.Builder().url(url).header("Authorization", credential)
            .addHeader("Accept", "application/vnd.horntell." + App.getVersion() + "+json")
            .addHeader("Content-Type", "text/json").put(body).build();

    com.squareup.okhttp.Response response = client.newCall(request).execute();

    return new Response(response);
}

From source file:com.howareyoudoing.data.net.RestApiImpl.java

License:Apache License

private String getUserEntitiesFromApi() throws MalformedURLException {
    String s = "{ \"token\": \"fdca03ce3cf55a3bc5612f91f69176e5632826118694a53ecf4e1622cfa5c7013b52a195faafe0bfe91bec406ed99735\", \"request\": { \"interface\": \"ServiceInterface\", \"method\": \"getAllUsers\", \"parameters\": { } } }";
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, s);
    return ApiConnection.createPOST(API_BASE_URL, body).requestSyncCall();
}

From source file:com.ibm.bluemix.appid.android.internal.userattributesmanager.UserAttributeManagerImpl.java

License:Apache License

private void sendProtectedRequest(String method, String name, String value, AccessToken accessToken,
        final UserAttributeResponseListener listener) {
    String url = Config.getUserProfilesServerUrl(AppID.getInstance()) + USER_PROFILE_ATTRIBUTES_PATH;
    url = (name == null || name.length() == 0) ? url : url + '/' + name;

    AppIDRequest req = new AppIDRequest(url, method);

    ResponseListener resListener = new ResponseListener() {
        @Override//w w  w  . j  a v  a  2s.  c  o  m
        public void onSuccess(Response response) {
            String responseText = response.getResponseText() == null || response.getResponseText().equals("")
                    ? "{}"
                    : response.getResponseText();
            try {
                listener.onSuccess(new JSONObject(responseText));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Response response, Throwable t, JSONObject extendedInfo) {
            String message = (t != null) ? t.getLocalizedMessage() : "";
            message = (extendedInfo != null) ? message + " : " + extendedInfo.toString() : message;
            logger.error(message);

            int errorCode = (response != null) ? response.getStatus() : 500;

            UserAttributesException.Error error;
            switch (errorCode) {
            case 401:
                error = UserAttributesException.Error.UNAUTHORIZED;
                break;
            case 404:
                error = UserAttributesException.Error.NOT_FOUND;
                break;
            default:
                error = UserAttributesException.Error.FAILED_TO_CONNECT;
                break;
            }
            listener.onFailure(new UserAttributesException(error));
        }
    };

    RequestBody requestBody = (value == null || value.length() == 0) ? null
            : RequestBody.create(MediaType.parse("application/json"), value);

    req.send(resListener, requestBody, accessToken);
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java

License:Apache License

/**
 * Send this resource request asynchronously, with the given string as the request body.
 * If no content type header was set, this method will set it to "text/plain".
 *
 * @param requestBody The request body text
 * @param listener    The listener whose onSuccess or onFailure methods will be called when this request finishes.
 *///  w  w  w  .  ja va  2 s .  co  m
protected void send(final String requestBody, final ResponseListener listener) {
    String contentType = headers.get(CONTENT_TYPE);

    if (contentType == null) {
        contentType = TEXT_PLAIN;
    }

    RequestBody body = RequestBody.create(MediaType.parse(contentType), requestBody);

    sendRequest(listener, body);
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java

License:Apache License

/**
 * Send this resource request asynchronously, with the given JSON object as the request body.
 * If no content type header was set, this method will set it to "application/json".
 *
 * @param json     The JSON object to put in the request body
 * @param listener The listener whose onSuccess or onFailure methods will be called when this request finishes.
 *///from w w w.j  av  a2  s.c  o m
protected void send(JSONObject json, ResponseListener listener) {
    String contentType = headers.get(CONTENT_TYPE);

    if (contentType == null) {
        contentType = JSON_CONTENT_TYPE;
    }

    RequestBody body = RequestBody.create(MediaType.parse(contentType), json.toString());

    sendRequest(listener, body);
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java

License:Apache License

/**
 * Send this resource request asynchronously, with the content of the given byte array as the request body.
 * Note that this method does not set any content type header, if such a header is required it must be set before calling this method.
 *
 * @param data     The byte array containing the request body
 * @param listener The listener whose onSuccess or onFailure methods will be called when this request finishes.
 *///from   w  ww.  jav a 2s.  c om
protected void send(byte[] data, ResponseListener listener) {
    RequestBody body = RequestBody.create(MediaType.parse(headers.get(CONTENT_TYPE)), data);

    sendRequest(listener, body);
}

From source file:com.ibm.watson.developer_cloud.alchemy.v1.AlchemyVision.java

License:Open Source License

/**
 * Executes the request and return the POJO that represent the response.
 * /*w w  w . jav  a 2 s .c om*/
 * @param <T> The POJO that represents the response object
 * @param params the request parameters
 * @param operation the alchemy operation
 * @param returnType the POJO class to be parsed from the response
 * @return the POJO object that represent the response
 */
private <T extends AlchemyGenericModel> T executeRequest(Map<String, Object> params, AlchemyAPI operation,
        Class<T> returnType) {
    final String inputType = getInputFormat(params, IMAGE, URL, HTML);
    final String path = AlchemyEndPoints.getPath(operation, inputType);

    final RequestBuilder requestBuilder = RequestBuilder.post(path);
    if (inputType == IMAGE) {
        if (params.get(IMAGE) instanceof String) {
            params.put(IMAGE_POST_MODE, NOT_RAW);
        } else {
            params.put(IMAGE_POST_MODE, RAW);
            final File image = (File) params.get(IMAGE);
            if (!image.exists()) {
                throw new IllegalArgumentException("The file: " + image.getAbsolutePath() + " does not exist.");
            } else {
                requestBuilder
                        .withBody(RequestBody.create(HttpMediaType.BINARY_FILE, (File) params.get(IMAGE)));
                params.remove(IMAGE);
            }
        }
    }

    // set json as default output mode
    params.put(OUTPUT_MODE, "json");

    // add all the parameters into the request as form-url-encoded parameters
    for (final String param : params.keySet()) {
        if (inputType.equals(IMAGE)) {
            requestBuilder.withQuery(param, params.get(param));
        } else {
            requestBuilder.withForm(param, params.get(param));
        }
    }

    return executeRequest(requestBuilder.build(), returnType);
}