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();
}
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);
}
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);
}
}
});
}
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());
}
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;
}
Aggregations