Search in sources :

Example 11 with OkHttpClient

use of okhttp3.OkHttpClient in project Tusky by Vavassor.

the class BaseActivity method createMastodonAPI.

protected void createMastodonAPI() {
    mastodonApiDispatcher = new Dispatcher();
    Gson gson = new GsonBuilder().registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()).registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()).create();
    OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder builder = originalRequest.newBuilder();
            String accessToken = getAccessToken();
            if (accessToken != null) {
                builder.header("Authorization", String.format("Bearer %s", accessToken));
            }
            Request newRequest = builder.build();
            return chain.proceed(newRequest);
        }
    }).dispatcher(mastodonApiDispatcher).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(getBaseUrl()).client(okHttpClient).addConverterFactory(GsonConverterFactory.create(gson)).build();
    mastodonAPI = retrofit.create(MastodonAPI.class);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) GsonBuilder(com.google.gson.GsonBuilder) SpannedTypeAdapter(com.keylesspalace.tusky.json.SpannedTypeAdapter) Request(okhttp3.Request) Gson(com.google.gson.Gson) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) StringWithEmojiTypeAdapter(com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter) MastodonAPI(com.keylesspalace.tusky.network.MastodonAPI) Interceptor(okhttp3.Interceptor) StringWithEmoji(com.keylesspalace.tusky.json.StringWithEmoji)

Example 12 with OkHttpClient

use of okhttp3.OkHttpClient in project cw-omnibus by commonsguy.

the class LoadThread method run.

@Override
public void run() {
    try {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(SO_URL).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            Reader in = response.body().charStream();
            BufferedReader reader = new BufferedReader(in);
            SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class);
            reader.close();
            EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
        } else {
            Log.e(getClass().getSimpleName(), response.toString());
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) BufferedReader(java.io.BufferedReader) BufferedReader(java.io.BufferedReader) Reader(java.io.Reader) Gson(com.google.gson.Gson)

Example 13 with OkHttpClient

use of okhttp3.OkHttpClient in project cw-omnibus by commonsguy.

the class Downloader method onHandleIntent.

@Override
public void onHandleIntent(Intent i) {
    mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    try {
        String filename = i.getData().getLastPathSegment();
        NotificationCompat.Builder builder = buildForeground(filename);
        final Notification notif = builder.build();
        startForeground(FOREGROUND_ID, notif);
        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        root.mkdirs();
        File output = new File(root, filename);
        if (output.exists()) {
            output.delete();
        }
        final ProgressResponseBody.Listener progressListener = new ProgressResponseBody.Listener() {

            long lastUpdateTime = 0L;

            @Override
            public void onProgressChange(long bytesRead, long contentLength, boolean done) {
                long now = SystemClock.uptimeMillis();
                if (now - lastUpdateTime > 1000) {
                    notif.contentView.setProgressBar(android.R.id.progress, (int) contentLength, (int) bytesRead, false);
                    mgr.notify(FOREGROUND_ID, notif);
                    lastUpdateTime = now;
                }
            }
        };
        Interceptor nightTrain = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response original = chain.proceed(chain.request());
                Response.Builder b = original.newBuilder().body(new ProgressResponseBody(original.body(), progressListener));
                return (b.build());
            }
        };
        OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(nightTrain).build();
        Request request = new Request.Builder().url(i.getData().toString()).build();
        Response response = client.newCall(request).execute();
        String contentType = response.header("Content-type");
        BufferedSink sink = Okio.buffer(Okio.sink(new File(output.getPath())));
        sink.writeAll(response.body().source());
        sink.close();
        stopForeground(true);
        raiseNotification(contentType, output, null);
    } catch (IOException e2) {
        stopForeground(true);
        raiseNotification(null, null, e2);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Notification(android.app.Notification) Response(okhttp3.Response) NotificationCompat(android.support.v4.app.NotificationCompat) File(java.io.File) Interceptor(okhttp3.Interceptor)

Example 14 with OkHttpClient

use of okhttp3.OkHttpClient in project cw-omnibus by commonsguy.

the class QuestionsFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View result = super.onCreateView(inflater, container, savedInstanceState);
    setRetainInstance(true);
    OkHttpClient.Builder okb = new OkHttpClient.Builder();
    TrustManagerBuilder tmb = new TrustManagerBuilder().withManifestConfig(getActivity());
    try {
        OkHttp3Integrator.applyTo(tmb, okb);
        OkHttpClient ok = okb.build();
        picasso = new Picasso.Builder(getActivity()).downloader(new OkHttp3Downloader(ok)).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.stackexchange.com").client(ok).addConverterFactory(GsonConverterFactory.create()).build();
        StackOverflowInterface so = retrofit.create(StackOverflowInterface.class);
        so.questions("android").enqueue(this);
    } catch (Exception e) {
        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
        Log.e(getClass().getSimpleName(), "Exception from TrustManagerBuilder setup", e);
    }
    return (result);
}
Also used : Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) TrustManagerBuilder(com.commonsware.cwac.netsecurity.TrustManagerBuilder) Picasso(com.squareup.picasso.Picasso) OkHttp3Downloader(com.jakewharton.picasso.OkHttp3Downloader) TrustManagerBuilder(com.commonsware.cwac.netsecurity.TrustManagerBuilder) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) ListView(android.widget.ListView) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 15 with OkHttpClient

use of okhttp3.OkHttpClient in project Gradle-demo by Arisono.

the class RetrofitImpl method initClient.

@Override
public void initClient() {
    // 本类保证初始化一次,减少系统开销
    Builder okBuilder = new OkHttpClient.Builder().connectTimeout(mbuilder.getConnectTimeout(), TimeUnit.SECONDS).readTimeout(mbuilder.getReadTimeout(), TimeUnit.SECONDS).writeTimeout(mbuilder.getWriteTimeout(), TimeUnit.SECONDS).sslSocketFactory(OkhttpUtils.createSSLSocketFactory(), // 信任所有证书
    new TrustAllCerts()).hostnameVerifier(new TrustAllHostnameVerifier());
    LogInterceptor logInterceptor = new LogInterceptor();
    logInterceptor.setBuilder(mbuilder);
    okBuilder.addInterceptor(logInterceptor);
    if (mbuilder.getCacheFileSize() != 0) {
        okBuilder.cache(new Cache(mbuilder.getCacheFile(), mbuilder.getCacheFileSize()));
        okBuilder.addInterceptor(new CacheInterceptor(String.valueOf(mbuilder.getCacheTime()), mbuilder.getCacheType()));
    }
    //后期缓存策略改进
    switch(mbuilder.getCacheType()) {
        case CacheType.ONLY_NETWORK:
            OkhttpUtils.println("CacheType.ONLY_NETWORK");
            break;
        case CacheType.ONLY_CACHED:
            OkhttpUtils.println("CacheType.ONLY_CACHED");
            break;
        case CacheType.CACHED_ELSE_NETWORK:
            break;
        case CacheType.NETWORK_ELSE_CACHED:
            break;
        default:
            break;
    }
    OkHttpClient client = okBuilder.build();
    retrofit = new Retrofit.Builder().client(client).baseUrl(mbuilder.getBaseUrl()).addConverterFactory(StringConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
}
Also used : Builder(okhttp3.OkHttpClient.Builder) Retrofit(retrofit2.Retrofit) TrustAllHostnameVerifier(com.gradle.android.retrofit.OkhttpUtils.TrustAllHostnameVerifier) OkHttpClient(okhttp3.OkHttpClient) Builder(okhttp3.OkHttpClient.Builder) LogInterceptor(com.gradle.android.Interceptor.LogInterceptor) CacheInterceptor(com.gradle.android.Interceptor.CacheInterceptor) TrustAllCerts(com.gradle.android.retrofit.OkhttpUtils.TrustAllCerts) Cache(okhttp3.Cache)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)632 Request (okhttp3.Request)359 Response (okhttp3.Response)302 IOException (java.io.IOException)196 Test (org.junit.Test)155 Call (okhttp3.Call)111 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)67 Retrofit (retrofit2.Retrofit)65 File (java.io.File)56 Interceptor (okhttp3.Interceptor)45 RequestBody (okhttp3.RequestBody)39 ResponseBody (okhttp3.ResponseBody)38 Cache (okhttp3.Cache)36 Gson (com.google.gson.Gson)33 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)33 Headers (okhttp3.Headers)33 Callback (okhttp3.Callback)32 GsonBuilder (com.google.gson.GsonBuilder)29 JSONObject (org.json.JSONObject)28 Provides (dagger.Provides)27