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

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

Introduction

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

Prototype

Request.Builder

Source Link

Usage

From source file:org.wso2.carbon.identity.authenticator.duo.DuoHttp.java

License:Open Source License

public Response executeHttpRequest() throws Exception {
    String url = "https://" + host + uri;
    String queryString = createQueryString();
    Request.Builder builder = new Request.Builder();
    if (method.equals("POST")) {
        builder.post(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("PUT")) {
        builder.put(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("GET")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }// w  w  w .  j a  v  a2  s . c o m
        builder.get();
    } else if (method.equals("DELETE")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }
        builder.delete();
    } else {
        throw new UnsupportedOperationException("Unsupported method: " + method);
    }
    Request request = builder.url(url).build();
    // Set up client.
    OkHttpClient httpclient = new OkHttpClient();
    if (proxy != null) {
        httpclient.setProxy(proxy);
    }
    httpclient.setConnectTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setWriteTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setReadTimeout(timeout, TimeUnit.SECONDS);
    // finish and execute request
    builder.headers(headers.build());
    return httpclient.newCall(builder.build()).execute();
}

From source file:pb.auth.OAuth.java

License:Apache License

public void generateAndSetAccessToken(String apiKey, String secret) throws ApiException {
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), "grant_type=client_credentials");
    Request authRequest = null;//  w w  w. ja  v a 2  s. c  o  m

    String authenticationHeader = base64Encode(apiKey + ":" + secret);
    authRequest = new Request.Builder().url("https://api.pitneybowes.com/oauth/token").post(body)
            .addHeader("Authorization", "Basic " + authenticationHeader).build();
    OkHttpClient client = new OkHttpClient().setAuthenticator(new TokenAuthenticator());

    try {
        Response response = client.newCall(authRequest).execute();
        Gson gson = new Gson();
        OAuthServiceResponce fromJson = gson.fromJson(response.body().string(), OAuthServiceResponce.class);
        setApiKey(apiKey);
        setSecret(secret);
        setAccessToken(fromJson.access_token);
    } catch (IOException e) {
        throw new ApiException(e);
    }

}

From source file:twitter4j.AlternativeHttpClientImpl.java

License:Apache License

@Override
HttpResponse handleRequest(HttpRequest req) throws TwitterException {
    prepareOkHttpClient();/* w ww .jav  a2 s. co  m*/

    HttpResponse res = null;
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(req.getURL()).headers(getHeaders(req));
    switch (req.getMethod()) {
    case HEAD:
    case DELETE:
    case PUT:
        break;
    case GET:
        requestBuilder.get();
        break;
    case POST:
        try {
            requestBuilder.post(getRequestBody(req));
        } catch (UnsupportedEncodingException e) {
            throw new TwitterException(e.getMessage(), e);
        }
        break;
    }
    final Request request = requestBuilder.build();

    int retriedCount;
    int retry = CONF.getHttpRetryCount() + 1;
    for (retriedCount = 0; retriedCount < retry; retriedCount++) {
        int responseCode = -1;
        try {
            Response response = okHttpClient.newCall(request).execute();
            lastRequestProtocol = response.header("OkHttp-Selected-Protocol");
            res = new OkHttpResponse(response, CONF);
            responseCode = response.code();

            if (logger.isDebugEnabled()) {
                logger.debug("Response: ");
                Map<String, List<String>> responseHeaders = res.getResponseHeaderFields();
                for (String key : responseHeaders.keySet()) {
                    List<String> values = responseHeaders.get(key);
                    for (String value : values) {
                        if (key != null) {
                            logger.debug(key + ": " + value);
                        } else {
                            logger.debug(value);
                        }
                    }
                }
            }
            if (responseCode < OK || (responseCode != FOUND && MULTIPLE_CHOICES <= responseCode)) {
                if (responseCode == ENHANCE_YOUR_CLAIM || responseCode == BAD_REQUEST
                        || responseCode < INTERNAL_SERVER_ERROR || retriedCount == CONF.getHttpRetryCount()) {

                    throw new TwitterException(res.asString(), res);
                }
            } else {
                break;
            }

        } catch (IOException e) {
            if (retriedCount == CONF.getHttpRetryCount()) {
                throw new TwitterException(e.getMessage(), e, responseCode);
            }
        }
        try {
            if (logger.isDebugEnabled() && res != null) {
                res.asString();
            }
            logger.debug("Sleeping " + CONF.getHttpRetryIntervalSeconds() + " seconds until the next retry.");
            Thread.sleep(CONF.getHttpRetryIntervalSeconds() * 1000);
        } catch (InterruptedException ignore) {
            //nothing to do
        }

    }
    return res;
}