Example usage for com.squareup.okhttp OkHttpClient newCall

List of usage examples for com.squareup.okhttp OkHttpClient newCall

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient newCall.

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

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  www  .  j a  va  2s.c  om*/
    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:me.drakeet.meizhi.ui.GankFragment.java

License:Open Source License

private void getOldVideoPreview(OkHttpClient client) {
    String url = "http://gank.io/" + String.format("%s/%s/%s", mYear, mMonth, mDay);
    Request request = new Request.Builder().url(url).build();
    client.newCall(request).enqueue(new Callback() {
        @Override// ww  w.  j  a va  2 s. c  o  m
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();
            mVideoPreviewUrl = LoveStrings.getVideoPreviewImageUrl(body);
            startPreview(mVideoPreviewUrl);
        }
    });
}

From source file:net.codestory.rest.RestResponse.java

License:Apache License

static RestResponse call(String url, Function<OkHttpClient, OkHttpClient> configureClient,
        Function<Request.Builder, Request.Builder> configureRequest) throws IOException {
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(ACCEPT_ALL);

    Request.Builder request = configureRequest.apply(new Request.Builder().url(url));
    OkHttpClient client = configureClient.apply(new OkHttpClient().setCookieHandler(cookieManager));

    Response response = client.newCall(request.build()).execute();

    return new RestResponse(cookieManager, response);
}

From source file:net.iquestria.java.iQuestria.java

public static void getUserById(Integer id, UserHandler callback) {
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(API_BASE + "/users/" + id + ".json").build();
    UserCallback userCallback = new UserCallback(callback);
    client.newCall(req).enqueue(userCallback);
}

From source file:net.iquestria.java.iQuestria.java

public static void getWorkById(Integer id, WorkHandler callback) {
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(API_BASE + "/works/" + id + ".json").build();
    WorkCallback workCallback = new WorkCallback(callback);
    client.newCall(req).enqueue(workCallback);
}

From source file:net.protyposis.android.mediaplayer.dash.DashParser.java

License:Open Source License

/**
 * Parses an MPD XML file. This needs to be executed off the main thread, else a
 * NetworkOnMainThreadException gets thrown.
 * @param source the URl of an MPD XML file
 * @return a MPD object//from  w  ww .  j av  a 2s  .  co  m
 * @throws android.os.NetworkOnMainThreadException if executed on the main thread
 */
public MPD parse(UriSource source) throws DashParserException {
    MPD mpd = null;
    OkHttpClient httpClient = new OkHttpClient();

    Headers.Builder headers = new Headers.Builder();
    if (source.getHeaders() != null && !source.getHeaders().isEmpty()) {
        for (String name : source.getHeaders().keySet()) {
            headers.add(name, source.getHeaders().get(name));
        }
    }

    Uri uri = source.getUri();

    Request.Builder request = new Request.Builder().url(uri.toString()).headers(headers.build());

    try {
        Response response = httpClient.newCall(request.build()).execute();
        if (!response.isSuccessful()) {
            throw new IOException("error requesting the MPD");
        }

        // Determine this MPD's default BaseURL by removing the last path segment (which is the MPD file)
        Uri baseUrl = Uri.parse(uri.toString().substring(0, uri.toString().lastIndexOf("/") + 1));

        // Get the current datetime from the server for live stream time syncing
        serverDate = response.headers().getDate("Date");

        // Parse the MPD file
        mpd = parse(response.body().byteStream(), baseUrl);
    } catch (IOException e) {
        Log.e(TAG, "error downloading the MPD", e);
        throw new DashParserException("error downloading the MPD", e);
    } catch (XmlPullParserException e) {
        Log.e(TAG, "error parsing the MPD", e);
        throw new DashParserException("error parsing the MPD", e);
    }

    return mpd;
}

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

License:Apache License

/**
 * ============Delivery============//from w w  w . ja v  a  2 s.c om
 */
protected void deliveryAsyncResult(OkHttpClient client, Request request, HttpCallback<?> callback) {
    Util.log("onDelivery:" + request.url().toString());
    Util.log("Headers:\n" + request.headers().toString());

    final HttpCallback<?> resCallBack = callback == null ? new DefaultCallback() : callback;

    //Call start
    callStart(resCallBack, request);

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            Util.log("onFailure:" + request.toString());
            callFailure(resCallBack, request, null, e);
            callFinish(resCallBack);
        }

        @Override
        public void onResponse(final Response response) {
            try {
                Object ret = null;
                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, resCallBack.getClass());
                }

                callSuccess(resCallBack, ret, response.code());
            } catch (Exception e) {
                Util.log("onResponse Failure:" + response.request().toString());
                callFailure(resCallBack, response.request(), response, e);
            }
            callFinish(resCallBack);
        }
    });
}

From source file:org.apache.hadoop.hdfs.web.oauth2.ConfRefreshTokenBasedAccessTokenProvider.java

License:Apache License

void refresh() throws IOException {
    try {//from  w ww .j  av  a  2 s  .  com
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);

        String bodyString = Utils.postBody(GRANT_TYPE, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken, CLIENT_ID,
                clientId);

        RequestBody body = RequestBody.create(URLENCODED, bodyString);

        Request request = new Request.Builder().url(refreshURL).post(body).build();
        Response responseBody = client.newCall(request).execute();

        if (responseBody.code() != HttpStatus.SC_OK) {
            throw new IllegalArgumentException("Received invalid http response: " + responseBody.code()
                    + ", text = " + responseBody.toString());
        }

        Map<?, ?> response = READER.readValue(responseBody.body().string());

        String newExpiresIn = response.get(EXPIRES_IN).toString();
        accessTokenTimer.setExpiresIn(newExpiresIn);

        accessToken = response.get(ACCESS_TOKEN).toString();
    } catch (Exception e) {
        throw new IOException("Exception while refreshing access token", e);
    }
}

From source file:org.apache.hadoop.hdfs.web.oauth2.CredentialBasedAccessTokenProvider.java

License:Apache License

void refresh() throws IOException {
    try {/*from   w ww  .j  ava  2  s .c  o  m*/
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);

        String bodyString = Utils.postBody(CLIENT_SECRET, getCredential(), GRANT_TYPE, CLIENT_CREDENTIALS,
                CLIENT_ID, clientId);

        RequestBody body = RequestBody.create(URLENCODED, bodyString);

        Request request = new Request.Builder().url(refreshURL).post(body).build();
        Response responseBody = client.newCall(request).execute();

        if (responseBody.code() != HttpStatus.SC_OK) {
            throw new IllegalArgumentException("Received invalid http response: " + responseBody.code()
                    + ", text = " + responseBody.toString());
        }

        Map<?, ?> response = READER.readValue(responseBody.body().string());

        String newExpiresIn = response.get(EXPIRES_IN).toString();
        timer.setExpiresIn(newExpiresIn);

        accessToken = response.get(ACCESS_TOKEN).toString();

    } catch (Exception e) {
        throw new IOException("Unable to obtain access token from credential", e);
    }
}

From source file:org.apache.nifi.processors.att.m2x.GetM2XStream.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String startTime = getLastStartTime(context, stateManager);
    final String streamUrl = getStreamUrl(apiUrl, deviceId, streamName, startTime);

    String responseBody;/*from  ww w .j  av a  2s. co  m*/
    try {
        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            return;
        }

        responseBody = response.body().string();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        return;
    }

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    try {
        final M2XStreamValues m2xValues = mapper.readValue(responseBody, M2XStreamValues.class);
        final List<M2XStreamValue> m2xValueList = m2xValues.getValues();

        if (!CollectionUtils.isEmpty(m2xValueList)) {
            for (final M2XStreamValue m2xValue : m2xValueList) {
                final DateTime timestamp = m2xValue.getTimestamp();
                final Object valueObj = m2xValue.getValue();
                final Set<Map.Entry<String, Object>> properties = m2xValue.getAdditionalProperties().entrySet();
                final ByteArrayInputStream bytes = new ByteArrayInputStream(
                        String.valueOf(valueObj).getBytes(StandardCharsets.UTF_8));

                FlowFile newFlowFile = session.create();
                newFlowFile = session.importFrom(bytes, newFlowFile);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.device.id", deviceId);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.name", streamName);
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.start",
                        m2xValues.getStart().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.end",
                        m2xValues.getEnd().toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.limit",
                        String.valueOf(m2xValues.getLimit()));
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.timestamp",
                        timestamp.toString());
                newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.millis",
                        String.valueOf(timestamp.getMillis()));
                for (final Map.Entry<String, Object> e : properties) {
                    newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value." + e.getKey(),
                            String.valueOf(e.getValue()));
                }

                session.getProvenanceReporter().create(newFlowFile);
                session.transfer(newFlowFile, REL_SUCCESS);
            }
        }

        setLastStartTime(stateManager, m2xValues.getEnd().toString());
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        context.yield();
    }
}