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:retrofit2.ToStringConverterFactory.java

License:Apache License

@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    if (String.class.equals(type)) {
        return new Converter<String, RequestBody>() {
            @Override/*from ww w.j  av a 2 s  .  c  o m*/
            public RequestBody convert(String value) throws IOException {
                return RequestBody.create(MEDIA_TYPE, value);
            }
        };
    }
    return null;
}

From source file:retrofit2.WireRequestBodyConverter.java

License:Apache License

@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    adapter.encode(buffer, value);/*from   ww  w.  j a  v a2s  . c o m*/
    return RequestBody.create(MEDIA_TYPE, buffer.snapshot());
}

From source file:ServerBatch.RequestServer.java

String doPostRequest(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

From source file:studio.imedia.vehicleinspection.activity.PersonalInfoActivity.java

/**
 * ?/*from w w w .j av a2s .com*/
 *
 * @param urlSB
 */
private void uploadAvatar(StringBuffer urlSB, File avatarFile) {
    String url = urlSB.toString();
    String filename = avatarFile.getName();
    File file = avatarFile;
    String avatarPath = null;

    // TODO 
    //        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
    RequestBody fileBody = RequestBody.create(Constant.Media.TYPE_JPEG, file);

    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addPart(Headers.of("Content-Disposition", "form-data; name=\"uploadFile\""), fileBody).build();

    Request request = new Request.Builder().url(url).post(requestBody).build();

    mClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            mHandler.sendEmptyMessage(CONNECT_FAIL);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String jsonStr = response.body().string();
            Log.d("files", jsonStr);
            try {
                int status = new JSONObject(jsonStr).getInt("status");
                Log.d("files", "the status is " + status);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

    // TODO ??
    //        Message msg = new Message();
    //        msg.what = MSG_UPLOAD_AVATAR_SUCCESS;
    //        msg.obj = avatarPath;
    //        mHandler.sendMessage(msg);
}

From source file:syncthing.api.SyncthingApiInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (!StringUtils.isEmpty(config.getApiKey())) {
        request = request.newBuilder()// w  w  w  .  j a va 2s.  c  o  m
                .addHeader(SyncthingApi.HEADER_API_KEY, StringUtils.trim(config.getApiKey())).build();
    } else if (!StringUtils.isEmpty(config.getAuth())) {
        request = request.newBuilder().addHeader("Authorization", StringUtils.trim(config.getAuth())).build();
    }
    if (config.isDebug()) {
        Timber.d(request.toString());
        if (StringUtils.equalsIgnoreCase(request.method(), "POST")) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            ByteString content = buffer.snapshot();
            Timber.d("body=%s", buffer.readString(Charset.defaultCharset()));
            MediaType type = request.body().contentType();
            request = request.newBuilder().post(RequestBody.create(type, content)).build();
        }
    }
    return chain.proceed(request);
}

From source file:twitter4j.AlternativeHttpClientImpl.java

License:Apache License

private RequestBody getRequestBody(HttpRequest req) throws UnsupportedEncodingException {
    if (HttpParameter.containsFile(req.getParameters())) {
        final String boundary = "----Twitter4J-upload" + System.currentTimeMillis();
        MultipartBuilder multipartBuilder = new MultipartBuilder(boundary).type(MultipartBuilder.FORM);
        for (HttpParameter parameter : req.getParameters()) {
            if (parameter.isFile()) {
                multipartBuilder.addPart(
                        Headers.of("Content-Disposition",
                                "form-data; name=\"" + parameter.getName() + "\"; filename=\""
                                        + parameter.getFile().getName() + "\""),
                        RequestBody.create(MediaType.parse(parameter.getContentType()), parameter.getFile()));
            } else {
                multipartBuilder.addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"" + parameter.getName() + "\""),
                        RequestBody.create(TEXT, parameter.getValue().getBytes("UTF-8")));
            }//w  ww  . j a  v  a 2 s  .  com
        }
        return multipartBuilder.build();
    } else {
        return RequestBody.create(FORM_URL_ENCODED,
                HttpParameter.encodeParameters(req.getParameters()).getBytes("UTF-8"));
    }
}

From source file:uk.co.caprica.brue.okhttp.service.bridge.AbstractBridgeService.java

License:Open Source License

/**
 *
 *
 * @param object// ww w . j  a v  a  2s .  c  o  m
 * @return
 */
private RequestBody requestBody(Object object) {
    try {
        String body = objectMapper.writer().writeValueAsString(object);
        return RequestBody.create(MediaType.parse(MEDIA_TYPE_JSON), body);
    } catch (IOException e) {
        throw new BridgeIOException(e);
    }
}

From source file:windows.webservices.utilidades.EjecutorJson.java

private Request prepararRequest() {
    Request.Builder build;//w w w  . ja v  a 2  s. c o  m

    if ((json == null || json.isEmpty()) && metodosDeEnvio.equals(MetodosDeEnvio.POST) && param != null) {
        json = "recibir datos por query param";
    }

    if (json != null && !json.equals("")) {
        build = new Request.Builder().url(uri.toString());
        RequestBody body = RequestBody.create(com.squareup.okhttp.MediaType.parse(MediaType.APPLICATION_JSON),
                json);
        build.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON).addHeader(HttpHeaders.CONTENT_TYPE,
                MediaType.APPLICATION_JSON);
        switch (metodosDeEnvio) {
        case POST:
            prepararParam();
            build.url(uri.toString()).post(body);
            break;
        case GET:
            build.method(metodosDeEnvio.getMetodo(), body);
            break;
        case PUT:
            prepararParam();
            build.url(uri.toString()).put(body);
            break;
        case DELETE:
            prepararParam();
            build.url(uri.toString()).delete(body);
            break;
        }
    } else {
        prepararParam();
        build = new Request.Builder().url(uri.toString());
        build.method(metodosDeEnvio.getMetodo(), null);

    }
    return build.build();
}