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:com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.java

License:Apache License

public Departures find(Context context, Site site) throws IllegalArgumentException, IOException {
    if (site == null) {
        Log.w(TAG, "Site is null");
        throw new IllegalArgumentException(TAG + ", Site is null");
    }//from www .j a  v  a  2s.  co m

    Log.d(TAG, "About to get departures for " + site.getName());
    String endpoint = apiEndpoint2() + "v1/departures/" + site.getId() + "?key=" + get(KEY) + "&timewindow=30";

    HttpHelper httpHelper = HttpHelper.getInstance(context);
    Request request = httpHelper.createRequest(endpoint);

    OkHttpClient client = httpHelper.getClient();

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

    if (!response.isSuccessful()) {
        Log.w(TAG, "A remote server error occurred when getting departures, status code: " + response.code());
        throw new IOException("A remote server error occurred when getting departures.");
    }

    Departures departures;
    String rawContent = response.body().string();
    try {
        departures = Departures.fromJson(new JSONObject(rawContent));
    } catch (JSONException e) {
        Crashlytics.logException(e);
        Log.d(TAG, "Could not parse the departure reponse.");
        throw new IOException("Could not parse the response.");
    }

    return departures;
}

From source file:com.massivcode.weatherinfoexam.utils.NetworkUtil.java

License:Apache License

/**
 * URL  ??  /*from  w w  w . ja  v a2s. c  om*/
 * @param urlString
 * @return
 * @throws IOException
 */
public static String getDataFromUrl(String urlString) throws IOException {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().url(urlString).build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

From source file:com.microsoft.windowsazure.mobileservices.http.ServiceFilterRequestImpl.java

License:Open Source License

@Override
public ServiceFilterResponse execute() throws Exception {
    // Execute request
    OkHttpClient client = mOkHttpClientFactory.createOkHttpClient();

    final Response response = client.newCall(mRequest).execute();

    ServiceFilterResponse serviceFilterResponse = new ServiceFilterResponseImpl(response);
    return serviceFilterResponse;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java

License:Open Source License

private boolean IsNetBackend() {
    try {/*www .  j  a  v  a 2s. c  o  m*/
        OkHttpClient httpclient = new OkHttpClient();

        Request request = new Request.Builder().url(getMobileServiceURL() + "api/runtimeinfo")
                .addHeader("ZUMO-API-VERSION", "2.0.0").build();

        Response response = httpclient.newCall(request).execute();

        String runtimeType;

        if (response.code() == 200) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            String responseString = response.body().string();

            JsonObject jsonResult = new JsonParser().parse(responseString).getAsJsonObject();

            runtimeType = jsonResult.get("runtime").getAsJsonObject().get("type").getAsString();

            out.close();
        } else {
            response.body().close();
            throw new IOException(String.valueOf(response.code()));
        }

        if (runtimeType.equals(".NET")) {
            return true;
        }

        return false;
    } catch (Exception ex) {
        return false;
    }
}

From source file:com.miz.functions.MizLib.java

License:Apache License

public static JSONObject getJSONObject(Context context, String url) {
    final OkHttpClient client = MizuuApplication.getOkHttpClient();

    Request request = new Request.Builder().url(url).get().build();

    try {//from   ww w  .  ja  v a2s . c om
        Response response = client.newCall(request).execute();

        if (response.code() >= 429) {
            // HTTP error 429 and above means that we've exceeded the query limit
            // for TMDb. Sleep for 5 seconds and try again.
            Thread.sleep(5000);
            response = client.newCall(request).execute();
        }
        return new JSONObject(response.body().string());
    } catch (Exception e) { // IOException and JSONException
        return new JSONObject();
    }
}

From source file:com.mobium.client.api.networking.WebHelper.java

License:Apache License

public static String downloadString(String url, OkHttpClient okHttpClient) throws IOException {
    Request request = new Request.Builder().url(url).get().addHeader("Accept-Encoding", "utf-8").build();
    byte[] data = okHttpClient.newCall(request).execute().body().bytes();
    return new String(data, "utf-8");
}

From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.java

License:Open Source 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);
    client.networkInterceptors().add(new MoesifOkHttp2Interceptor());

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.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 ww.j  ava  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:com.monmonja.library.server.JsonRpcRequest.java

License:Open Source License

public void run(OkHttpClient client, final Success success, final Failure failure) {
    client.newCall(this.request).enqueue(new Callback() {
        @Override//from www.ja v  a 2s. c  o  m
        public void onFailure(Request request, IOException e) {
            failure.failure(e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String responseData = response.body().string();
            JsonResponse jsonResponse = gson.fromJson(responseData, JsonResponse.class);
            if (jsonResponse.result != null) {
                success.success(gson.fromJson(jsonResponse.result, clazz));
            } else {
                Log.d("JsonRpc", responseData);
                failure.failure("JSONPRC2 error");
                //                    successHandler.sendEmptyMessage(0);
            }
        }
    });
}

From source file:com.mycelium.lt.api.LtApiClient.java

License:Apache License

private Response getConnectionAndSendRequest(LtRequest request, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();

    // Figure what our current endpoint is. On errors we fail over until we
    // are back at the initial endpoint
    HttpEndpoint initialEndpoint = getEndpoint();
    while (true) {
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {/*from  w  w w .  j a  v  a 2  s  .c  om*/
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("LT connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            // configure TimeOuts
            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder()
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(request.toString()).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("LtApi %s finished (%dms)", request.toString(),
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format("Local Trader server request for class %s returned HTTP status code %d",
                        request.getClass().toString(), response.code()));
            }

        } catch (IOException e) {
            logError("getConnectionAndSendRequest failed IO exception.");
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }

        // We had an IO exception or a bad status, fail over and try again
        _serverEndpoints.switchToNextEndpoint();
        // Check if we are back at the initial endpoint, in which case we have
        // to give up
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }
    }
}

From source file:com.mycelium.wapi.api.WapiClient.java

License:Apache License

/**
 * Attempt to connect and send to a URL in our list of URLS, if it fails try
 * the next until we have cycled through all URLs. timeout.
 *//*  ww w.java  2s.  c o m*/
private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();
    while (true) {
        // currently active server-endpoint
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            // configure TimeOuts
            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode)
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("Wapi %s finished (%dms)", function,
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format("Http call to %s failed with %d %s", function, response.code(),
                        response.message()));
                // throw...
            }
        } catch (IOException e) {
            logError("IOException when sending request " + function, e);
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }
        // Try the next server
        _serverEndpoints.switchToNextEndpoint();
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }

    }
}