Example usage for com.squareup.okhttp Request.Builder url

List of usage examples for com.squareup.okhttp Request.Builder url

Introduction

In this page you can find the example usage for com.squareup.okhttp Request.Builder url.

Prototype

HttpUrl url

To view the source code for com.squareup.okhttp Request.Builder url.

Click Source Link

Usage

From source file:com.cinchapi.concourse.http.HttpTest.java

License:Apache License

/**
 * Perform a GET request/*from   w w  w . j av  a  2  s  . c  o m*/
 * 
 * @param route
 * @param args - include a {@link Headers} object to set the request headers
 * @return the response
 */
protected Response get(String route, Object... args) {
    try {
        Request.Builder builder = new Request.Builder();
        args = filterArgs(builder, args);
        args = cleanUrlArgs(args);
        route = MessageFormat.format(route, args);
        Request request = builder.url(base + route).get().build();
        Response response = http.newCall(request).execute();
        long ts = response.hashCode();
        Variables.register("request_" + ts, request);
        Variables.register("response_" + ts, response);
        return response;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.cinchapi.concourse.http.HttpTest.java

License:Apache License

/**
 * Perform a POST request./*from   w w  w.  ja v  a  2s  .c om*/
 * 
 * @param route
 * @param data
 * @param args - include a {@link Headers} object to set the request headers
 * @return the response
 */
protected Response post(String route, String data, Object... args) {
    try {
        RequestBody body = RequestBody.create(JSON, data);
        Request.Builder builder = new Request.Builder();
        args = filterArgs(builder, args);
        args = cleanUrlArgs(args);
        route = MessageFormat.format(route, args);
        Request request = builder.url(base + route).post(body).build();
        Response response = http.newCall(request).execute();
        long ts = response.hashCode();
        Variables.register("request_" + ts, request);
        Variables.register("response_" + ts, response);
        return response;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.cinchapi.concourse.http.HttpTest.java

License:Apache License

/**
 * Perform a PUT request.//from   w  ww .  j  av  a2s. c om
 * 
 * @param route
 * @param data
 * @param args - include a {@link Headers} object to set the request headers
 * @return the response
 */
protected Response put(String route, String data, Object... args) {
    try {
        RequestBody body = RequestBody.create(JSON, data);
        Request.Builder builder = new Request.Builder();
        args = filterArgs(builder, args);
        args = cleanUrlArgs(args);
        route = MessageFormat.format(route, args);
        Request request = builder.url(base + route).put(body).build();
        Response response = http.newCall(request).execute();
        long ts = response.hashCode();
        Variables.register("request_" + ts, request);
        Variables.register("response_" + ts, response);
        return response;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java

License:Open Source License

@Override
public URLHttpResponse performRequest(Request<?> request, ArrayList<HttpParamsEntry> additionalHeaders)
        throws IOException {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    for (final HttpParamsEntry entry : request.getHeaders()) {
        okHttpRequestBuilder.addHeader(entry.k, entry.v);
    }/* w w w . j  av a  2 s.c om*/
    for (final HttpParamsEntry entry : additionalHeaders) {
        okHttpRequestBuilder.addHeader(entry.k, entry.v);
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);
    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    return responseFromConnection(okHttpResponse);
}

From source file:com.enstage.wibmo.util.HttpUtil.java

License:Apache License

public static String postDataUseOkHttp(String posturl, byte postData[], boolean useCache, MediaType mediaType)
        throws Exception {
    URL url;//  w  w  w . ja  va  2 s .c om
    long stime = System.currentTimeMillis();
    try {
        url = new URL(posturl);

        RequestBody body = RequestBody.create(mediaType, postData);

        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (useCache == false) {
            builder.addHeader("Cache-Control", "no-cache");
        }
        builder.post(body);
        Request request = builder.build();

        if (okhttpinit == false) {
            Log.w(TAG, "WibmoSDK init was false; " + client.getSslSocketFactory());

            if (client.getSslSocketFactory() == null) {
                setSSLstuff();
            }
        }

        Response res = client.newCall(request).execute();

        // Read the response.
        if (res.code() != HttpURLConnection.HTTP_OK) {
            Log.e(TAG, "Bad res code: " + res.code());
            Log.e(TAG, "Url was: " + posturl.toString());
            Log.e(TAG, "HTTP response: " + res.message() + "; " + res.body().string());
            return null;
        }

        return res.body().string();
    } finally {
        long etime = System.currentTimeMillis();
        Log.i(TAG, "time dif: " + (etime - stime));
    }
}

From source file:com.example.jony.myapp.reader_APP.ui.DailyDetailsActivity.java

License:Open Source License

@Override
protected void onDataRefresh() {
    Request.Builder builder = new Request.Builder();
    builder.url(url);
    Request request = builder.build();
    HttpUtil.enqueue(request, new Callback() {
        @Override/*from ww w .  j a  v  a  2  s. c  o m*/
        public void onFailure(Request request, IOException e) {
            handler.sendEmptyMessage(CONSTANT.ID_FAILURE);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String res = response.body().string();
            DebugUtils.DLog(res);
            Gson gson = new Gson();
            dailyDetailsBean = gson.fromJson(res, DailyDetailsBean.class);

            cache.execSQL(DailyTable.updateBodyContent(DailyTable.NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getBody()));
            cache.execSQL(DailyTable.updateBodyContent(DailyTable.COLLECTION_NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getBody()));
            cache.execSQL(DailyTable.updateLargePic(DailyTable.NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getImage()));
            cache.execSQL(DailyTable.updateLargePic(DailyTable.COLLECTION_NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getImage()));

            imageUrl = dailyDetailsBean.getImage();
            body = dailyDetailsBean.getBody();

            handler.sendEmptyMessage(CONSTANT.ID_SUCCESS);
        }
    });
}

From source file:com.facebook.buck.artifact_cache.HttpArtifactCache.java

License:Apache License

protected void storeImpl(ImmutableSet<RuleKey> ruleKeys, final ImmutableMap<String, String> metadata,
        final Path file, final Finished.Builder eventBuilder) throws IOException {
    // Build the request, hitting the multi-key endpoint.
    Request.Builder builder = new Request.Builder();
    builder.url(uri.resolve("/artifacts/key").toURL());

    final HttpArtifactCacheBinaryProtocol.StoreRequest storeRequest = new HttpArtifactCacheBinaryProtocol.StoreRequest(
            ruleKeys, metadata, new ByteSource() {
                @Override/* w w w .  j a  v a  2  s.co  m*/
                public InputStream openStream() throws IOException {
                    return projectFilesystem.newFileInputStream(file);
                }
            });

    eventBuilder.setRequestSizeBytes(storeRequest.getContentLength());

    // Wrap the file into a `RequestBody` which uses `ProjectFilesystem`.
    builder.put(new RequestBody() {
        @Override
        public MediaType contentType() {
            return OCTET_STREAM;
        }

        @Override
        public long contentLength() throws IOException {
            return storeRequest.getContentLength();
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
            StoreWriteResult writeResult = storeRequest.write(bufferedSink.outputStream());
            eventBuilder.setArtifactSizeBytes(writeResult.getArtifactSizeBytes());
            eventBuilder.setArtifactContentHash(writeResult.getArtifactContentHashCode().toString());
        }
    });

    // Dispatch the store operation and verify it succeeded.
    Request request = builder.build();
    Response response = storeCall(request);
    final boolean requestFailed = response.code() != HttpURLConnection.HTTP_ACCEPTED;
    if (requestFailed) {
        reportFailure("store(%s, %s): unexpected response: %d", uri, ruleKeys, response.code());
    }

    eventBuilder.setWasUploadSuccessful(!requestFailed);
}

From source file:com.facebook.buck.slb.LoadBalancedService.java

License:Apache License

@Override
public Response makeRequest(String path, Request.Builder requestBuilder) throws IOException {
    URI server = slb.getBestServer();
    LoadBalancedServiceEventData.Builder data = LoadBalancedServiceEventData.builder().setServer(server);
    requestBuilder.url(SingleUriService.getFullUrl(server, path));
    Request request = requestBuilder.build();
    if (request.body() != null && request.body().contentLength() != -1) {
        data.setRequestSizeBytes(request.body().contentLength());
    }//from www.  j  ava  2  s .co m
    Call call = client.newCall(request);
    try {
        Response response = call.execute();
        if (response.body() != null && response.body().contentLength() != -1) {
            data.setResponseSizeBytes(response.body().contentLength());
        }
        slb.reportRequestSuccess(server);
        return response;
    } catch (IOException e) {
        data.setException(e);
        slb.reportRequestException(server);
        throw new IOException(e);
    } finally {
        eventBus.post(new LoadBalancedServiceEvent(data.build()));
    }
}

From source file:com.facebook.buck.slb.SingleUriService.java

License:Apache License

@Override
public Response makeRequest(String path, Request.Builder requestBuilder) throws IOException {
    requestBuilder.url(getFullUrl(server, path));
    return client.newCall(requestBuilder.build()).execute();
}

From source file:com.frostwire.util.http.OKHTTPClient.java

License:Open Source License

private Request.Builder prepareRequestBuilder(OkHttpClient okHttpClient, String url, int timeout,
        String userAgent, String referrer, String cookie) {
    okHttpClient.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
    okHttpClient.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);
    okHttpClient.interceptors().clear();
    Request.Builder builder = new Request.Builder();
    builder.url(url);
    if (!StringUtils.isNullOrEmpty(userAgent)) {
        builder.header("User-Agent", userAgent);
    }// ww w .j a  v  a 2  s . c  o m
    if (!StringUtils.isNullOrEmpty(referrer)) {
        builder.header("Referer", referrer); // [sic - typo in HTTP protocol]
    }
    if (!StringUtils.isNullOrEmpty(cookie)) {
        builder.header("Cookie", cookie);
    }
    return builder;
}