Search in sources :

Example 56 with OkHttpClient

use of okhttp3.OkHttpClient in project ride-read-android by Ride-Read.

the class RetrofitUtils method configClient.

private static OkHttpClient configClient() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS).readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS).writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    //                .retryOnConnectionFailure(true);
    try {
        final X509TrustManager tm = new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
            }
        };
        final SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
        builder.sslSocketFactory(sc.getSocketFactory(), tm).hostnameVerifier((hostname, session) -> hostname.contains(".195."));
        if (BuildConfig.DEBUG) {
            // Log信息拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //设置 Debug Log 模式
            builder.addInterceptor(loggingInterceptor);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) GsonBuilder(com.google.gson.GsonBuilder) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 57 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 58 with OkHttpClient

use of okhttp3.OkHttpClient in project Android by Tracman-org.

the class LoginActivity method authenticateWithTracmanServer.

private void authenticateWithTracmanServer(final Request request) throws Exception {
    // Needed to support TLS 1.1 and 1.2
    //		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
    //				TrustManagerFactory.getDefaultAlgorithm());
    //		trustManagerFactory.init((KeyStore) null);
    //		TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    //		if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    //			throw new IllegalStateException("Unexpected default trust managers:"
    //					+ Arrays.toString(trustManagers));
    //		}
    //		X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
    OkHttpClient client = new OkHttpClient.Builder().build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            //Log.e(TAG, "Failed to connect to Tracman server!");
            showError(R.string.server_connection_error);
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response res) throws IOException {
            if (!res.isSuccessful()) {
                showError(R.string.login_no_user_error);
                res.body().close();
                throw new IOException("Unexpected code: " + res);
            } else {
                //Log.d(TAG, "Response code: " + res.code());
                String userString = res.body().string();
                System.out.println("Full response: " + userString);
                String userID, userName, userSK;
                try {
                    JSONObject user = new JSONObject(userString);
                    userID = user.getString("_id");
                    userName = user.getString("name");
                    userSK = user.getString("sk32");
                //Log.v(TAG, "User retrieved with ID: " + userID);
                } catch (JSONException e) {
                    //Log.e(TAG, "Unable to parse user JSON: ", e);
                    //Log.e(TAG, "JSON String used: " + userString);
                    userID = null;
                    userName = null;
                    userSK = null;
                }
                // Save user as loggedInUser
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("loggedInUser", userString);
                editor.putString("loggedInUserId", userID);
                editor.putString("loggedInUserName", userName);
                editor.putString("loggedInUserSk", userSK);
                editor.commit();
                startActivityForResult(new Intent(LoginActivity.this, SettingsActivity.class), SIGN_OUT);
            }
        }
    });
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) SharedPreferences(android.content.SharedPreferences) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) ResultCallback(com.google.android.gms.common.api.ResultCallback) JSONObject(org.json.JSONObject)

Example 59 with OkHttpClient

use of okhttp3.OkHttpClient in project AntennaPod by AntennaPod.

the class NetworkUtils method getFeedMediaSizeObservable.

public static Observable<Long> getFeedMediaSizeObservable(FeedMedia media) {
    return Observable.create(new Observable.OnSubscribe<Long>() {

        @Override
        public void call(Subscriber<? super Long> subscriber) {
            if (!NetworkUtils.isDownloadAllowed()) {
                subscriber.onNext(0L);
                subscriber.onCompleted();
                return;
            }
            long size = Integer.MIN_VALUE;
            if (media.isDownloaded()) {
                File mediaFile = new File(media.getLocalMediaUrl());
                if (mediaFile.exists()) {
                    size = mediaFile.length();
                }
            } else if (!media.checkedOnSizeButUnknown()) {
                // only query the network if we haven't already checked
                String url = media.getDownload_url();
                if (TextUtils.isEmpty(url)) {
                    subscriber.onNext(0L);
                    subscriber.onCompleted();
                    return;
                }
                OkHttpClient client = AntennapodHttpClient.getHttpClient();
                Request.Builder httpReq = new Request.Builder().url(url).header("Accept-Encoding", "identity").head();
                try {
                    Response response = client.newCall(httpReq.build()).execute();
                    if (response.isSuccessful()) {
                        String contentLength = response.header("Content-Length");
                        try {
                            size = Integer.parseInt(contentLength);
                        } catch (NumberFormatException e) {
                            Log.e(TAG, Log.getStackTraceString(e));
                        }
                    }
                } catch (IOException e) {
                    subscriber.onNext(0L);
                    subscriber.onCompleted();
                    Log.e(TAG, Log.getStackTraceString(e));
                    // better luck next time
                    return;
                }
            }
            Log.d(TAG, "new size: " + size);
            if (size <= 0) {
                // they didn't tell us the size, but we don't want to keep querying on it
                media.setCheckedOnSizeButUnknown();
            } else {
                media.setSize(size);
            }
            subscriber.onNext(size);
            subscriber.onCompleted();
            DBWriter.setFeedMedia(media);
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread());
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) File(java.io.File)

Example 60 with OkHttpClient

use of okhttp3.OkHttpClient in project AntennaPod by AntennaPod.

the class ItunesSearchFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_itunes_search, container, false);
    gridView = (GridView) root.findViewById(R.id.gridView);
    adapter = new ItunesAdapter(getActivity(), new ArrayList<>());
    gridView.setAdapter(adapter);
    //Show information about the podcast when the list item is clicked
    gridView.setOnItemClickListener((parent, view1, position, id) -> {
        Podcast podcast = searchResults.get(position);
        if (!podcast.feedUrl.contains("itunes.apple.com")) {
            Intent intent = new Intent(getActivity(), OnlineFeedViewActivity.class);
            intent.putExtra(OnlineFeedViewActivity.ARG_FEEDURL, podcast.feedUrl);
            intent.putExtra(OnlineFeedViewActivity.ARG_TITLE, "iTunes");
            startActivity(intent);
        } else {
            gridView.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
            subscription = Observable.create((Observable.OnSubscribe<String>) subscriber -> {
                OkHttpClient client = AntennapodHttpClient.getHttpClient();
                Request.Builder httpReq = new Request.Builder().url(podcast.feedUrl).header("User-Agent", ClientConfig.USER_AGENT);
                try {
                    Response response = client.newCall(httpReq.build()).execute();
                    if (response.isSuccessful()) {
                        String resultString = response.body().string();
                        JSONObject result = new JSONObject(resultString);
                        JSONObject results = result.getJSONArray("results").getJSONObject(0);
                        String feedUrl = results.getString("feedUrl");
                        subscriber.onNext(feedUrl);
                    } else {
                        String prefix = getString(R.string.error_msg_prefix);
                        subscriber.onError(new IOException(prefix + response));
                    }
                } catch (IOException | JSONException e) {
                    subscriber.onError(e);
                }
                subscriber.onCompleted();
            }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(feedUrl -> {
                progressBar.setVisibility(View.GONE);
                gridView.setVisibility(View.VISIBLE);
                Intent intent = new Intent(getActivity(), OnlineFeedViewActivity.class);
                intent.putExtra(OnlineFeedViewActivity.ARG_FEEDURL, feedUrl);
                intent.putExtra(OnlineFeedViewActivity.ARG_TITLE, "iTunes");
                startActivity(intent);
            }, error -> {
                Log.e(TAG, Log.getStackTraceString(error));
                progressBar.setVisibility(View.GONE);
                gridView.setVisibility(View.VISIBLE);
                String prefix = getString(R.string.error_msg_prefix);
                new MaterialDialog.Builder(getActivity()).content(prefix + " " + error.getMessage()).neutralText(android.R.string.ok).show();
            });
        }
    });
    progressBar = (ProgressBar) root.findViewById(R.id.progressBar);
    txtvError = (TextView) root.findViewById(R.id.txtvError);
    butRetry = (Button) root.findViewById(R.id.butRetry);
    txtvEmpty = (TextView) root.findViewById(android.R.id.empty);
    loadToplist();
    return root;
}
Also used : Bundle(android.os.Bundle) GridView(android.widget.GridView) ProgressBar(android.widget.ProgressBar) SearchView(android.support.v7.widget.SearchView) ItunesAdapter(de.danoeh.antennapod.adapter.itunes.ItunesAdapter) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Intent(android.content.Intent) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Observable(rx.Observable) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) MenuItemUtils(de.danoeh.antennapod.menuhandler.MenuItemUtils) MenuInflater(android.view.MenuInflater) Locale(java.util.Locale) Menu(android.view.Menu) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Button(android.widget.Button) Response(okhttp3.Response) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Log(android.util.Log) Request(okhttp3.Request) LayoutInflater(android.view.LayoutInflater) R(de.danoeh.antennapod.R) MenuItemCompat(android.support.v4.view.MenuItemCompat) Fragment(android.support.v4.app.Fragment) ClientConfig(de.danoeh.antennapod.core.ClientConfig) IOException(java.io.IOException) ViewGroup(android.view.ViewGroup) URLEncoder(java.net.URLEncoder) List(java.util.List) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) Podcast(de.danoeh.antennapod.adapter.itunes.ItunesAdapter.Podcast) OnlineFeedViewActivity(de.danoeh.antennapod.activity.OnlineFeedViewActivity) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Subscription(rx.Subscription) JSONArray(org.json.JSONArray) ItunesAdapter(de.danoeh.antennapod.adapter.itunes.ItunesAdapter) OnlineFeedViewActivity(de.danoeh.antennapod.activity.OnlineFeedViewActivity) OkHttpClient(okhttp3.OkHttpClient) ArrayList(java.util.ArrayList) Podcast(de.danoeh.antennapod.adapter.itunes.ItunesAdapter.Podcast) Request(okhttp3.Request) Intent(android.content.Intent) IOException(java.io.IOException) GridView(android.widget.GridView) SearchView(android.support.v7.widget.SearchView) View(android.view.View) TextView(android.widget.TextView) Observable(rx.Observable) Response(okhttp3.Response) JSONObject(org.json.JSONObject)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)149 Request (okhttp3.Request)73 Response (okhttp3.Response)61 IOException (java.io.IOException)52 Test (org.junit.Test)35 Call (okhttp3.Call)24 Retrofit (retrofit2.Retrofit)24 Interceptor (okhttp3.Interceptor)19 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)18 MockResponse (okhttp3.mockwebserver.MockResponse)18 File (java.io.File)15 GsonBuilder (com.google.gson.GsonBuilder)12 Provides (dagger.Provides)12 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)12 Gson (com.google.gson.Gson)10 ArrayList (java.util.ArrayList)10 List (java.util.List)10 Cache (okhttp3.Cache)10 Observable (rx.Observable)10 Singleton (javax.inject.Singleton)9