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.sonaive.v2ex.util.LoginHelper.java

License:Open Source License

/** After spent hours digging, I give up */
private void signIn(String onceCode) {

    Map<String, String> params = new HashMap<>();
    params.put("next", "/");
    params.put("u", mAccountName);
    params.put("p", mPassword);
    params.put("once", onceCode);

    RequestBody postBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), params.toString());

    Request request = new Request.Builder().header("Origin", "http://www.v2ex.com")
            .header("Referer", "http://www.v2ex.com/signin").header("X-Requested-With", "com.android.browser")
            .header("Cache-Control", "max-age=0")
            .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
            .header("Accept-Language", "zh-CN, en-US")
            .header("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7")
            .url(Api.API_URLS.get(Api.API_SIGNIN)).post(postBody).build();

    try {//  w w  w  . ja v  a  2s. co  m

        okHttpClient.setFollowRedirects(false);
        Response response = okHttpClient.newCall(request).execute();

        final JsonObject result = new JsonObject();
        Pattern errorPattern = Pattern.compile("<div class=\"problem\">(.*)</div>");
        Matcher errorMatcher = errorPattern.matcher(response.body().string());
        final String errorContent;

        if (response.code() == 302) {// temporary moved, 302 found, disallow redirects.
            LOGD(TAG, "sign in success!");
            getUserInfo();
            return;
        } else if (errorMatcher.find()) {
            errorContent = errorMatcher.group(1).replaceAll("<[^>]+>", "");
        } else {
            errorContent = "Unknown error";
        }

        if (errorContent != null) {
            result.addProperty("result", "fail");
            result.addProperty("err_msg", errorContent);
            LOGD(TAG, "sign in error, err_msg = " + errorContent);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.spotify.apollo.http.client.HttpClient.java

License:Apache License

@Override
public CompletionStage<com.spotify.apollo.Response<ByteString>> send(com.spotify.apollo.Request apolloRequest,
        Optional<com.spotify.apollo.Request> apolloIncomingRequest) {

    final Optional<RequestBody> requestBody = apolloRequest.payload().map(payload -> {
        final MediaType contentType = apolloRequest.header("Content-Type").map(MediaType::parse)
                .orElse(DEFAULT_CONTENT_TYPE);
        return RequestBody.create(contentType, payload);
    });/*from w  w  w.jav  a2s  .  c  om*/

    Headers.Builder headersBuilder = new Headers.Builder();
    apolloRequest.headers().asMap().forEach((k, v) -> headersBuilder.add(k, v));

    apolloIncomingRequest.flatMap(req -> req.header(AUTHORIZATION_HEADER))
            .ifPresent(header -> headersBuilder.add(AUTHORIZATION_HEADER, header));

    final Request request = new Request.Builder().method(apolloRequest.method(), requestBody.orElse(null))
            .url(apolloRequest.uri()).headers(headersBuilder.build()).build();

    final CompletableFuture<com.spotify.apollo.Response<ByteString>> result = new CompletableFuture<>();

    //https://github.com/square/okhttp/wiki/Recipes#per-call-configuration
    OkHttpClient finalClient = client;
    if (apolloRequest.ttl().isPresent() && client.getReadTimeout() != apolloRequest.ttl().get().toMillis()) {
        finalClient = client.clone();
        finalClient.setReadTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS);
    }

    finalClient.newCall(request).enqueue(TransformingCallback.create(result));

    return result;
}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

Call postImage(Callback callback) throws Throwable {
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addPart(Headers.of("Content-Disposition", "form-data; name=\"image_request[locale]\""),
                    RequestBody.create(null, "en-US"))
            .addPart(//from   w  w  w .  ja v a 2  s  .  c om
                    Headers.of("Content-Disposition",
                            "form-data; name=\"image_request[image]\"; filename=\"testimage.jpg\""),
                    RequestBody.create(MEDIA_TYPE_JPG, new File(fileUri.getPath())))
            .build();

    Request request = new Request.Builder().header("Authorization", "CloudSight " + CLOUDSIGHT_KEY).url(reqUrl)
            .post(requestBody).build();

    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}

From source file:com.tohelpyou.client.manager.HttpManager.java

License:Apache License

/**POST
 * @param url_ ?url/*from   w  ww.  ja  va2 s . c o  m*/
 * @param request 
 * @param requestCode
 *            ?onActivityResult??activity?????
 *            {@link OnHttpResponseListener#onHttpResponse(int, String, Exception)}<br/>
 *            ??requestCode??
 * @param listener
 */
public void post(final String url_, final com.alibaba.fastjson.JSONObject request, final int requestCode,
        final OnHttpResponseListener listener) {
    if (request == null || request.containsKey(JSONRequest.KEY_TAG) == false) {
        throw new IllegalArgumentException("post  " + url_ + " \n"
                + "   request == null || request.containsKey(JSONRequest.KEY_TAG) == false !!!");
    }

    new AsyncTask<Void, Void, Exception>() {

        String result;

        @Override
        protected Exception doInBackground(Void... params) {

            try {
                String url = StringUtil.getNoBlankString(url_);

                OkHttpClient client = getHttpClient(url);
                if (client == null) {
                    return new Exception(TAG + ".post  AsyncTask.doInBackground  client == null >> return;");
                }
                String body = JSON.toJSONString(request);
                Log.d(TAG, "\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n post  url = " + url_ + "\n request = \n"
                        + body);

                RequestBody requestBody = RequestBody.create(TYPE_JSON, body);

                result = getResponseJson(client, new Request.Builder().addHeader(KEY_TOKEN, getToken(url))
                        .url(StringUtil.getNoBlankString(url)).post(requestBody).build());
                Log.d(TAG, "\n post  result = \n" + result + "\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n");
            } catch (Exception e) {
                Log.e(TAG, "post  AsyncTask.doInBackground  try {  result = getResponseJson(..."
                        + "} catch (Exception e) {\n" + e.getMessage());
                return e;
            }

            return null;
        }

        @Override
        protected void onPostExecute(Exception exception) {
            super.onPostExecute(exception);
            listener.onHttpResponse(requestCode, result, exception);
        }

    }.execute();
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

License:Apache License

public Response doRest(String path, String requestBody, HttpVerb verb) throws IOException, RestApiException {
    OkHttpClient client = new OkHttpClient();

    Optional<String> gerritAuthOptional = updateGerritAuthWhenRequired(client);

    String uri = authData.getHost();
    // only use /a when http login is required (i.e. we haven't got a gerrit-auth cookie)
    // it would work in most cases also with /a, but it breaks with HTTP digest auth ("Forbidden" returned)
    if (authData.isLoginAndPasswordAvailable() && !gerritAuthOptional.isPresent()) {
        uri += "/a";
    }//from  w ww  .  ja  v a  2 s .c om
    uri += path;

    Request.Builder builder = new Request.Builder().url(uri).addHeader("Accept", MEDIA_TYPE_JSON.toString());

    if (verb == HttpVerb.GET) {
        builder = builder.get();
    } else if (verb == HttpVerb.DELETE) {
        builder = builder.delete();
    } else {
        if (requestBody == null) {
            builder.method(verb.toString(), null);
        } else {
            builder.method(verb.toString(), RequestBody.create(MEDIA_TYPE_JSON, requestBody));
        }
    }

    if (gerritAuthOptional.isPresent()) {
        builder.addHeader("X-Gerrit-Auth", gerritAuthOptional.get());
    }

    return httpRequestExecutor.execute(client, builder);
}

From source file:com.wialon.remote.OkSdkHttpClient.java

License:Apache License

@Override
public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) {
    //Method will work at 2.1 version of library https://github.com/square/okhttp/issues/963 and https://github.com/square/okhttp/pull/969
    MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    RequestBody paramsBody = paramsMapToRequestBody(params);
    if (paramsBody != null) {
        builder.addPart(paramsBody);//from  ww w  . j  ava 2s  .  c om
    }
    builder.addPart(RequestBody.create(MediaType.parse(""), file));
    Request request = new Request.Builder().url(url).post(builder.build()).build();
    threadPool.submit(new HttpRequest(getHttpClient(timeout), request, callback));
}

From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java

License:Open Source License

@Override
public void uploadTestRun(String testSpecificationId, FilePath workspace, String includes, String excludes,
        Map<String, Object> metadata, PrintStream logger) throws IOException, InterruptedException {
    if (testSpecificationId == null || testSpecificationId.isEmpty()) {
        throw new IllegalArgumentException(
                "No test specification id specified. Does the test specification still exist in XL TestView?");
    }//from w ww  .  j a va2  s.co  m
    try {
        logInfo(logger,
                format("Collecting files from '%s' using include pattern: '%s' and exclude pattern '%s'",
                        workspace.getRemote(), includes, excludes));

        DirScanner scanner = new DirScanner.Glob(includes, excludes);

        ObjectMapper objectMapper = new ObjectMapper();

        RequestBody body = new MultipartBuilder().type(MultipartBuilder.MIXED)
                .addPart(RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF_8),
                        objectMapper.writeValueAsString(metadata)))
                .addPart(new ZipRequestBody(workspace, scanner, logger)).build();

        Request request = new Request.Builder()
                .url(createSensibleURL(API_IMPORT + "/" + testSpecificationId, serverUrl))
                .header("User-Agent", getUserAgent()).header("Accept", APPLICATION_JSON_UTF_8)
                .header("Authorization", createCredentials()).header("Transfer-Encoding", "chunked").post(body)
                .build();

        Response response = client.newCall(request).execute();
        ObjectMapper mapper = createMapper();
        ImportError importError;
        switch (response.code()) {
        case 200:
            logInfo(logger, "Sent data successfully");
            return;
        case 304:
            logWarn(logger, "No new results were detected. Nothing was imported.");
            throw new IllegalStateException("No new results were detected. Nothing was imported.");
        case 400:
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        case 401:
            throw new AuthenticationException(String.format(
                    "User '%s' and the supplied password are unable to log in", credentials.getUsername()));
        case 402:
            throw new PaymentRequiredException("The XL TestView server does not have a valid license");
        case 404:
            throw new ConnectionException("Cannot find test specification '" + testSpecificationId
                    + ". Please check if the XL TestView server is "
                    + "running and the test specification exists.");
        case 422:
            logWarn(logger, "Unable to process results.");
            logWarn(logger,
                    "Are you sure your include/exclude pattern provides all needed files for the test tool?");
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        default:
            throw new IllegalStateException("Unknown error. Status code: " + response.code()
                    + ". Response message: " + response.toString());
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        e.printStackTrace();
        LOG.warn("I/O error uploading test run data to {} {}\n{}", serverUrl.toString(), e.toString(), e);
        throw new IOException(
                "I/O error uploading test run data to " + serverUrl.toString() + " " + e.toString(), e);
    }
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAllowsRawBody() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class)
            .body(RequestBody.create(MediaType.parse("application/text"), "Hey!"));
    // Build the CallSpec so that we can build the request.
    builder.build();//from  w w w.  j av  a 2s .c  o  m

    Request request = builder.request();
    RequestBody body = request.body();
    assertThat(body.contentLength()).isEqualTo(4);
    assertThat(body.contentType().subtype()).isEqualTo("text");

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("Hey!");
}

From source file:com.xing.api.resources.ProfileEditingResourceTest.java

License:Apache License

@Test
public void updateOwnProfilePicture() throws Exception {
    // This is not a valid body, but the server prevents that in the real world.
    PictureUpload upload = PictureUpload.pictureUploadJPEG("picture.jpeg", new byte[0]);
    testVoidSpec(resource.updateProfilePicture(upload));

    RecordedRequest request = server.takeRequest(500, TimeUnit.MILLISECONDS);
    Buffer body = request.getBody();
    assertThat(body.readUtf8()).isEqualTo("{\"photo\":{" + "\"content\":[]," + "\"file_name\":\"picture.jpeg\","
            + "\"mime_type\":\"image/jpeg\"" + "}}");

    testVoidSpec(resource.updateProfilePicture(RequestBody.create(MediaType.parse("multipart/form-data"), "")));
}

From source file:com.yandex.disk.rest.RequestBodyProgress.java

License:Apache License

/**
 * Returns a new request body that transmits the content of {@code file}.
 * <br/>//from w  w  w  . j a va 2s.  com
 * Based on {@link RequestBody#create(com.squareup.okhttp.MediaType, File)}
 *
 * @see RequestBody#create(com.squareup.okhttp.MediaType, File)
 */
/* package */ static RequestBody create(final MediaType contentType, final File file, final long startOffset,
        final ProgressListener listener) {
    if (file == null) {
        throw new NullPointerException("content == null");
    }

    if (listener == null && startOffset == 0) {
        return RequestBody.create(contentType, file);
    }

    return new RequestBody() {

        private void updateProgress(long loaded) throws CancelledUploadingException {
            if (listener != null) {
                if (listener.hasCancelled()) {
                    throw new CancelledUploadingException();
                }
                listener.updateProgress(loaded + startOffset, file.length());
            }
        }

        @Override
        public MediaType contentType() {
            return contentType;
        }

        @Override
        public long contentLength() {
            return file.length() - startOffset;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = null;
            InputStream inputStream = new FileInputStream(file);
            try {
                if (startOffset > 0) {
                    long skipped = inputStream.skip(startOffset);
                    if (skipped != startOffset) {
                        throw new IOException("RequestBodyProgress: inputStream.skip() failed");
                    }
                }
                long loaded = 0;
                updateProgress(loaded);
                source = Okio.source(inputStream);
                Buffer buffer = new Buffer();
                for (long readCount; (readCount = source.read(buffer, SIZE)) != -1;) {
                    sink.write(buffer, readCount);
                    loaded += readCount;
                    updateProgress(loaded);
                }
                logger.debug("loaded: " + loaded);
            } finally {
                Util.closeQuietly(source);
                Util.closeQuietly(inputStream);
            }
        }
    };
}