Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

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

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

From source file:com.sonaive.v2ex.sync.api.UserIdentityApi.java

License:Open Source License

public void verifyUserIdentity(final String accountName,
        final WeakReference<LoginHelper.Callbacks> callbacksRef) {

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(mUrl + "?username=" + accountName).build();

    okHttpClient.newCall(request).enqueue(new Callback() {

        @Override//from  www.  j  av a2  s .  co  m
        public void onFailure(Request request, IOException e) {
            JsonObject result = new JsonObject();
            result.addProperty("result", "fail");
            result.addProperty("err_msg", "IOException");
            if (callbacksRef != null) {
                callbacksRef.get().onIdentityCheckedFailed(result);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            JsonObject result = new JsonObject();
            if (response.code() == 200) {
                String responseBody = response.body().string();
                try {
                    JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
                    String status = jsonObject.get("status").getAsString();
                    if (status != null && status.equals("found")) {
                        result.addProperty("result", "ok");
                        LOGD(TAG, "userInfo: " + responseBody);
                        AccountUtils.setActiveAccount(mContext, accountName);
                        V2exDataHandler dataHandler = new V2exDataHandler(mContext);

                        Bundle data = new Bundle();
                        data.putString(Api.ARG_RESULT, responseBody);
                        data.putString(V2exDataHandler.ARG_DATA_KEY, V2exDataHandler.DATA_KEY_MEMBERS);
                        dataHandler.applyData(new Bundle[] { data });

                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedSuccess(result);
                        }
                    } else if (status != null && status.equals("notfound")) {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_user_not_found));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    } else {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_unknown_error));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    }
                } catch (JsonSyntaxException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "JsonSyntaxException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                } catch (UnsupportedOperationException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "UnsupportedOperationException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                }
            } else if (response.code() == 403) {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", "403 Forbidden");
                if (callbacksRef != null) {
                    callbacksRef.get().onIdentityCheckedFailed(result);
                }
            }
            LOGD(TAG, "responseCode: " + response.code() + ", result: " + result.get("result") + ", err_msg: "
                    + result.get("err_msg"));
        }
    });
}

From source file:com.sonaive.v2ex.ui.BaseActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Glide.get(this).register(GlideUrl.class, InputStream.class,
            new OkHttpUrlLoader.Factory(new OkHttpClient()));

    mHandler = new Handler();
    imageLoader = new ImageLoader(this);

    ActionBar ab = getSupportActionBar();
    if (ab != null) {
        ab.setDisplayHomeAsUpEnabled(true);
    }/*from w  w  w.  jav  a2 s. co m*/

    mLUtils = LUtils.getInstance(this);
    mThemedStatusBarColor = getResources().getColor(R.color.theme_primary_dark);
    mNormalStatusBarColor = mThemedStatusBarColor;

    SyncUtils.createSyncAccount(this);
    getLoaderManager().restartLoader(0, buildLoaderArgs(), new AccountLoader());
}

From source file:com.sonaive.v2ex.util.LoginHelper.java

License:Open Source License

/** Starts the helper. Call this from your Activity's onStart(). */
public void start() {
    Activity activity = getActivity("start()");
    if (activity == null) {
        return;//from www  .ja v  a2s .co  m
    }

    if (mStarted) {
        LOGW(TAG, "Helper already started. Ignoring redundant call.");
        return;
    }

    mStarted = true;
    LOGD(TAG, "Helper starting. Connecting " + mAccountName);

    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient();
    }

    mUserIdentityApi.verifyUserIdentity(mAccountName, mCallbacksRef);
}

From source file:com.sphereon.sdk.template.processor.handler.ApiClient.java

License:Apache License

public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;/*from w  w w . j  av  a2  s.  co  m*/

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime.
     * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date (without time).
    this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/0.1.2-SNAPSHOT/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put("oauth2schema", new OAuth());
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}

From source file:com.spotify.apollo.http.client.HttpClient.java

License:Apache License

/**
 * @return a HttpClient with the default configuration settings.
 */// w w  w . j a  v a 2 s .  c om
public static HttpClient createUnconfigured() {
    return new HttpClient(new OkHttpClient());
}

From source file:com.spotify.apollo.http.client.OkHttpClientProvider.java

License:Apache License

@Override
public OkHttpClient get() {
    final OkHttpClient client = new OkHttpClient();

    //timeouts settings
    config.connectTimeoutMillis().ifPresent(millis -> client.setConnectTimeout(millis, TimeUnit.MILLISECONDS));

    config.readTimeoutMillis().ifPresent(millis -> client.setReadTimeout(millis, TimeUnit.MILLISECONDS));

    config.writeTimeoutMillis().ifPresent(millis -> client.setWriteTimeout(millis, TimeUnit.MILLISECONDS));

    // connection pool settings
    client.setConnectionPool(new ConnectionPool(
            // defaults that come from com.squareup.okhttp.ConnectionPool
            config.maxIdleConnections().orElse(5),
            config.connectionKeepAliveDurationMillis().orElse(5 * 60 * 1000)));

    // async dispatcher settings
    config.maxAsyncRequests().ifPresent(max -> client.getDispatcher().setMaxRequests(max));

    config.maxAsyncRequestsPerHost().ifPresent(max -> client.getDispatcher().setMaxRequestsPerHost(max));

    closer.register(ExecutorServiceCloser.of(client.getDispatcher().getExecutorService()));

    return client;
}

From source file:com.spotify.apollo.httpservice.HttpServiceTest.java

License:Apache License

@Test
public void shouldPopulateRequestMetadata() throws Exception {
    AtomicReference<RequestMetadata> metadataReference = new AtomicReference<>();

    final InstanceWaiter waiter = new InstanceWaiter();

    Future<?> future = executorService.submit(() -> {
        try {/*from w  w  w.  j a  va2  s.co  m*/
            HttpService.boot(
                    environment -> environment.routingEngine()
                            .registerRoute(Route.async("GET", "/meta", trackMeta(metadataReference))),
                    "metadatatest", waiter);
        } catch (LoadingException e) {
            throw new RuntimeException(e);
        }
    });

    final Service.Instance instance = waiter.waitForInstance();

    Request httpRequest = new Request.Builder().url("http://localhost:29432/meta").build();

    new OkHttpClient().newCall(httpRequest).execute();

    assertThat(((HttpRequestMetadata) metadataReference.get()).httpVersion(), is("HTTP/1.1"));

    instance.getSignaller().signalShutdown();
    instance.waitForShutdown();
    future.get();
}

From source file:com.squareup.main.okhttp.HttpHandler.java

License:Apache License

@Override
protected URLConnection openConnection(URL url) throws IOException {
    return new OkHttpClient().open(url);
}

From source file:com.squareup.main.okhttp.HttpHandler.java

License:Apache License

@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
    if (url == null || proxy == null) {
        throw new IllegalArgumentException("url == null || proxy == null");
    }/*  w w  w . j a  v  a 2s  .c  om*/
    return new OkHttpClient().setProxy(proxy).open(url);
}

From source file:com.squareup.picasso.OkHttp3DownloaderTest.java

License:Apache License

@Test
public void shutdownClosesCache() throws Exception {
    OkHttpClient client = new OkHttpClient();
    Cache cache = new Cache(temporaryFolder.getRoot(), 100);
    client.setCache(cache);/*  w  w w  .j  a  va  2 s  .  c o  m*/
    new OkHttpDownloader(client).shutdown();
    assertThat(cache.isClosed()).isTrue();
}