Example usage for com.squareup.okhttp Call execute

List of usage examples for com.squareup.okhttp Call execute

Introduction

In this page you can find the example usage for com.squareup.okhttp Call execute.

Prototype

public Response execute() throws IOException 

Source Link

Document

Invokes the request immediately, and blocks until the response can be processed or is in error.

Usage

From source file:de.schildbach.wallet.ExchangeRatesProvider.java

License:Open Source License

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);/*  www  .j a v  a  2s  .  c  o m*/
    request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final String content = response.body().string();

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content);
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = Strings.emptyToNull(i.next());
                if (currencyCode != null && !"timestamp".equals(currencyCode)
                        && !MonetaryFormat.CODE_BTC.equals(currencyCode)
                        && !MonetaryFormat.CODE_MBTC.equals(currencyCode)
                        && !MonetaryFormat.CODE_UBTC.equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final Fiat rate = Fiat.parseFiat(currencyCode, rateStr);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new org.bitcoinj.utils.ExchangeRate(rate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}", currencyCode, url,
                                        x.getMessage());
                            }
                        }
                    }
                }
            }

            watch.stop();
            log.info("fetched exchange rates from {}, {} chars, took {}", url, content.length(), watch);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    }

    return null;
}

From source file:de.schildbach.wallet.ui.AlertDialogsFragment.java

License:Open Source License

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    log.debug("querying \"{}\"...", versionUrl);
    final Request.Builder request = new Request.Builder();
    request.url(versionUrl);// w ww . j  ava  2s.  c  o m
    request.header("Accept-Charset", "utf-8");
    final String userAgent = application.httpUserAgent();
    if (userAgent != null)
        request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());

    backgroundHandler.post(new Runnable() {
        @Override
        public void run() {
            boolean abort = false;
            try {
                final Response response = call.execute();
                if (response.isSuccessful()) {
                    final long serverTime = response.headers().getDate("Date").getTime();
                    try (final BufferedReader reader = new BufferedReader(response.body().charStream())) {
                        abort = handleServerTime(serverTime);

                        while (true) {
                            final String line = reader.readLine();
                            if (line == null)
                                break;
                            if (line.charAt(0) == '#')
                                continue;

                            final Splitter splitter = Splitter.on('=').trimResults();
                            final Iterator<String> split = splitter.split(line).iterator();
                            if (!split.hasNext())
                                continue;
                            final String key = split.next();
                            if (!split.hasNext()) {
                                abort = handleLine(key);
                                if (abort)
                                    break;
                                continue;
                            }
                            final String value = split.next();
                            if (!split.hasNext()) {
                                abort = handleProperty(key, value);
                                if (abort)
                                    break;
                                continue;
                            }
                            log.info("Ignoring line: {}", line);
                        }
                    }
                }
            } catch (final Exception x) {
                handleException(x);
            }
            if (!abort)
                handleCatchAll();
        }
    });
}

From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

License:Open Source License

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override//from w  w w.  jav  a 2s.c o  m
        public void run() {
            org.bitcoinj.core.Context.propagate(Constants.CONTEXT);

            final HttpUrl.Builder url = HttpUrl.parse(Constants.BITEASY_API_URL).newBuilder();
            url.addPathSegment("outputs");
            url.addQueryParameter("per_page", "MAX");
            url.addQueryParameter("operator", "AND");
            url.addQueryParameter("spent_state", "UNSPENT");
            for (final Address address : addresses)
                url.addQueryParameter("address[]", address.toBase58());

            log.debug("trying to request wallet balance from {}", url.build());

            final Request.Builder request = new Request.Builder();
            request.url(url.build());
            request.cacheControl(new CacheControl.Builder().noCache().build());
            request.header("Accept-Charset", "utf-8");
            if (userAgent != null)
                request.header("User-Agent", userAgent);

            final Call call = Constants.HTTP_CLIENT.newCall(request.build());
            try {
                final Response response = call.execute();
                if (response.isSuccessful()) {
                    final String content = response.body().string();
                    final JSONObject json = new JSONObject(content);

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IOException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        final Sha256Hash uxtoHash = Sha256Hash.wrap(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = Constants.HEX
                                .decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);

                        if (tx.getOutputs().size() > uxtoIndex) {
                            // Work around not being able to replace outputs on transactions
                            final List<TransactionOutput> outputs = new ArrayList<TransactionOutput>(
                                    tx.getOutputs());
                            final TransactionOutput dummy = outputs.set(uxtoIndex, output);
                            checkState(dummy.getValue().equals(Coin.NEGATIVE_SATOSHI),
                                    "Index %s must be dummy output", uxtoIndex);
                            // Remove and re-add all outputs
                            tx.clearOutputs();
                            for (final TransactionOutput o : outputs)
                                tx.addOutput(o);
                        } else {
                            // Fill with dummies as needed
                            while (tx.getOutputs().size() < uxtoIndex)
                                tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                        Coin.NEGATIVE_SATOSHI, new byte[] {}));

                            // Add the real output
                            tx.addOutput(output);
                        }
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final int responseCode = response.code();
                    final String responseMessage = response.message();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);
                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            }
        }
    });
}

From source file:de.schildbach.wallet.util.HttpGetThread.java

License:Open Source License

@Override
public void run() {
    log.debug("querying \"{}\"...", url);

    final Request.Builder request = new Request.Builder();
    request.url(url);/*w w  w. j a  v a 2s .  co  m*/
    request.header("Accept-Charset", "utf-8");
    if (userAgent != null)
        request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final long serverTime = response.headers().getDate("Date").getTime();
            final BufferedReader reader = new BufferedReader(response.body().charStream());
            final String line = reader.readLine().trim();
            reader.close();

            handleLine(line, serverTime);
        }
    } catch (final Exception x) {
        handleException(x);
    }
}

From source file:io.kodokojo.commons.utils.docker.DockerSupport.java

License:Open Source License

private boolean tryRequest(HttpUrl url, OkHttpClient httpClient, ServiceIsUp serviceIsUp) {
    Response response = null;//from   w  w  w. j  ava2 s  .c  om
    try {
        Request request = new Request.Builder().url(url).get().build();
        Call call = httpClient.newCall(request);
        response = call.execute();
        boolean isSuccesseful = serviceIsUp.accept(response);
        response.body().close();
        return isSuccesseful;
    } catch (IOException e) {
        return false;
    } finally {
        if (response != null) {
            try {
                response.body().close();
            } catch (IOException e) {
                LOGGER.warn("Unable to close response.");
            }
        }
    }
}

From source file:io.kubernetes.client.util.Watch.java

License:Apache License

/**
 * Creates a watch on a TYPENAME (T) using an API Client and a Call object.
 * @param client the API client//from w w w . j  a  v  a 2 s  .c  o m
 * @param call the call object returned by api.{ListOperation}Call(...)
 *             method. Make sure watch flag is set in the call.
 * @param watchType The type of the WatchResponse&lt;T&gt;. Use something like
 *                  new TypeToken&lt;Watch.Response&lt;TYPENAME&gt;&gt;(){}.getType()
 * @param <T> TYPENAME.
 * @return Watch object on TYPENAME
 * @throws ApiException on IO exceptions.
 */
public static <T> Watch<T> createWatch(ApiClient client, Call call, Type watchType) throws ApiException {
    try {
        com.squareup.okhttp.Response response = call.execute();
        if (!response.isSuccessful()) {
            String respBody = null;
            if (response.body() != null) {
                try {
                    respBody = response.body().string();
                } catch (IOException e) {
                    throw new ApiException(response.message(), e, response.code(),
                            response.headers().toMultimap());
                }
            }
            throw new ApiException(response.message(), response.code(), response.headers().toMultimap(),
                    respBody);
        }
        return new Watch<>(client.getJSON(), response.body(), watchType);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:it.smartcommunitylab.ApiClient.java

License:Apache License

public Response executeSimple(Call call, Type returnType) throws ApiException {
    try {//w  w w.j  av  a  2  s  .co m
        return call.execute();
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:keywhiz.client.KeywhizClient.java

License:Apache License

public boolean isLoggedIn() throws IOException {
    HttpUrl url = baseUrl.resolve("/admin/me");
    Call call = client.newCall(new Request.Builder().get().url(url).build());
    return call.execute().code() != HttpStatus.SC_UNAUTHORIZED;
}

From source file:library.util.OkHttpStack.java

License:Apache License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    Builder okHttpRequestBuilder = new Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from  w w w  .  j a  v  a  2 s .c  o m
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

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

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

protected <T> T deliveryResult(Class<T> tClass, Request request, HttpCallback<?> callback) {
    Util.log("onDelivery:" + request.url().toString());
    Util.log("Headers:\n" + request.headers().toString());
    if (callback == null && tClass == null)
        callback = new DefaultCallback();
    final Class<?> subClass = tClass == null ? callback.getClass() : tClass;

    callStart(callback, request);//from w  w w.  j av  a 2 s.  co m
    Call call = mOkHttpClient.newCall(request);
    Response response = null;
    Object ret = null;
    try {
        response = call.execute();
        final String string = response.body().string();
        final boolean haveValue = !TextUtils.isEmpty(string);

        Util.log("onResponse:Code:%d Body:%s.", response.code(), (haveValue ? string : "null"));

        if (haveValue) {
            ret = mResolver.analysis(string, subClass);
        }

        callSuccess(callback, ret, response.code());
    } catch (Exception e) {
        Request req = response == null ? request : response.request();
        Util.log("onResponse Failure:" + req.toString());
        callFailure(callback, req, response, e);
    }
    callFinish(callback);
    return (T) ret;
}