Upgrade to OkHttp3

This commit is contained in:
Martin Fietz 2016-11-13 22:04:08 +01:00
parent 4a6b630e56
commit 2682cbd784
12 changed files with 120 additions and 111 deletions

View File

@ -139,8 +139,8 @@ dependencies {
compile "commons-io:commons-io:$commonsioVersion"
compile "org.jsoup:jsoup:$jsoupVersion"
compile "com.github.bumptech.glide:glide:$glideVersion"
compile "com.squareup.okhttp:okhttp:$okhttpVersion"
compile "com.squareup.okhttp:okhttp-urlconnection:$okhttpVersion"
compile "com.squareup.okhttp3:okhttp:$okhttpVersion"
compile "com.squareup.okhttp3:okhttp-urlconnection:$okhttpVersion"
compile "com.squareup.okio:okio:$okioVersion"
compile "de.greenrobot:eventbus:$eventbusVersion"
compile "io.reactivex:rxandroid:$rxAndroidVersion"

View File

@ -53,7 +53,7 @@
public *;
}
-dontwarn com.squareup.okhttp.**
-dontwarn okhttp3.**
-dontwarn okio.**
# for RxJava:

View File

@ -228,6 +228,7 @@ public class EpisodesApplyActionFragment extends Fragment {
case R.id.check_has_media:
checkWithMedia();
resId = R.string.selected_has_media_label;
break;
case R.id.sort_title_a_z:
sortByTitle(false);
return true;

View File

@ -18,10 +18,6 @@ import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.internal.MDButton;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.net.InetSocketAddress;
@ -33,6 +29,10 @@ import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.service.download.AntennapodHttpClient;
import de.danoeh.antennapod.core.service.download.ProxyConfig;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
@ -258,10 +258,11 @@ public class ProxyDialog {
SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
Proxy proxy = new Proxy(proxyType, address);
OkHttpClient client = AntennapodHttpClient.newHttpClient();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setProxy(proxy);
client.interceptors().clear();
OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.proxy(proxy);
builder.interceptors().clear();
OkHttpClient client = builder.build();
if(!TextUtils.isEmpty(username)) {
String credentials = Credentials.basic(username, password);
client.interceptors().add(chain -> {

View File

@ -18,9 +18,6 @@ import android.widget.ProgressBar;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
@ -39,6 +36,9 @@ import de.danoeh.antennapod.adapter.itunes.ItunesAdapter;
import de.danoeh.antennapod.core.ClientConfig;
import de.danoeh.antennapod.core.service.download.AntennapodHttpClient;
import de.danoeh.antennapod.menuhandler.MenuItemUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

View File

@ -52,8 +52,8 @@ project.ext {
iconifyVersion = "2.2.2"
jsoupVersion = "1.9.2"
materialDialogsVersion = "0.8.5.8@aar"
okhttpVersion = "2.7.5"
okioVersion = "1.9.0"
okhttpVersion = "3.4.2"
okioVersion = "1.11.0"
recyclerviewFlexibledividerVersion = "1.2.6"
robotiumSoloVersion = "5.6.0"
rxAndroidVersion = "1.2.1"

View File

@ -56,9 +56,9 @@ dependencies {
compile "com.jayway.android.robotium:robotium-solo:$robotiumSoloVersion"
compile "org.jsoup:jsoup:$jsoupVersion"
compile "com.github.bumptech.glide:glide:$glideVersion"
compile "com.github.bumptech.glide:okhttp-integration:$glideOkhttpIntegrationVersion"
compile "com.squareup.okhttp:okhttp:$okhttpVersion"
compile "com.squareup.okhttp:okhttp-urlconnection:$okhttpVersion"
compile "com.github.bumptech.glide:okhttp3-integration:$glideOkhttpIntegrationVersion@aar"
compile "com.squareup.okhttp3:okhttp:$okhttpVersion"
compile "com.squareup.okhttp3:okhttp-urlconnection:$okhttpVersion"
compile "com.squareup.okio:okio:$okioVersion"
compile "com.nineoldandroids:library:2.4.0"
compile "de.greenrobot:eventbus:$eventbusVersion"

View File

@ -4,15 +4,12 @@ import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.bumptech.glide.integration.okhttp.OkHttpStreamFetcher;
import com.bumptech.glide.integration.okhttp3.OkHttpStreamFetcher;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.io.InputStream;
@ -22,9 +19,13 @@ import de.danoeh.antennapod.core.service.download.AntennapodHttpClient;
import de.danoeh.antennapod.core.service.download.HttpDownloader;
import de.danoeh.antennapod.core.storage.DBReader;
import de.danoeh.antennapod.core.util.NetworkUtils;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* @see com.bumptech.glide.integration.okhttp.OkHttpUrlLoader
* @see com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
*/
public class ApOkHttpUrlLoader implements ModelLoader<String, InputStream> {
@ -42,9 +43,10 @@ public class ApOkHttpUrlLoader implements ModelLoader<String, InputStream> {
if (internalClient == null) {
synchronized (Factory.class) {
if (internalClient == null) {
internalClient = AntennapodHttpClient.newHttpClient();
internalClient.interceptors().add(new NetworkAllowanceInterceptor());
internalClient.interceptors().add(new BasicAuthenticationInterceptor());
OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder();
builder.interceptors().add(new NetworkAllowanceInterceptor());
builder.interceptors().add(new BasicAuthenticationInterceptor());
internalClient = builder.build();
}
}
}
@ -113,8 +115,8 @@ public class ApOkHttpUrlLoader implements ModelLoader<String, InputStream> {
@Override
public Response intercept(Chain chain) throws IOException {
com.squareup.okhttp.Request request = chain.request();
String url = request.urlString();
Request request = chain.request();
String url = request.url().toString();
String authentication = DBReader.getImageAuthentication(url);
if(TextUtils.isEmpty(authentication)) {
@ -125,7 +127,7 @@ public class ApOkHttpUrlLoader implements ModelLoader<String, InputStream> {
// add authentication
String[] auth = authentication.split(":");
String credentials = HttpDownloader.encodeCredentials(auth[0], auth[1], "ISO-8859-1");
com.squareup.okhttp.Request newRequest = request
Request newRequest = request
.newBuilder()
.addHeader("Authorization", credentials)
.build();

View File

@ -1,15 +1,6 @@
package de.danoeh.antennapod.core.gpoddernet;
import android.support.annotation.NonNull;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@ -38,6 +29,13 @@ import de.danoeh.antennapod.core.gpoddernet.model.GpodnetTag;
import de.danoeh.antennapod.core.gpoddernet.model.GpodnetUploadChangesResponse;
import de.danoeh.antennapod.core.preferences.GpodnetPreferences;
import de.danoeh.antennapod.core.service.download.AntennapodHttpClient;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Communicates with the gpodder.net service.
@ -570,15 +568,7 @@ public class GpodnetService {
e.printStackTrace();
throw new GpodnetServiceException(e);
} finally {
if (response != null && body != null) {
try {
body.close();
} catch (IOException e) {
e.printStackTrace();
throw new GpodnetServiceException(e);
}
}
body.close();
}
return responseString;
}
@ -605,12 +595,7 @@ public class GpodnetService {
throw new GpodnetServiceException(e);
} finally {
if (body != null) {
try {
body.close();
} catch (IOException e) {
e.printStackTrace();
throw new GpodnetServiceException(e);
}
body.close();
}
}
return result;
@ -619,12 +604,7 @@ public class GpodnetService {
private String getStringFromResponseBody(@NonNull ResponseBody body)
throws GpodnetServiceException {
ByteArrayOutputStream outputStream;
int contentLength = 0;
try {
contentLength = (int) body.contentLength();
} catch (IOException ignore) {
// ignore
}
int contentLength = (int) body.contentLength();
if (contentLength > 0) {
outputStream = new ByteArrayOutputStream(contentLength);
} else {

View File

@ -5,12 +5,6 @@ import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.http.StatusLine;
import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
@ -20,16 +14,27 @@ import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.storage.DBWriter;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.http.StatusLine;
/**
* Provides access to a HttpClient singleton.
@ -50,13 +55,13 @@ public class AntennapodHttpClient {
*/
public static synchronized OkHttpClient getHttpClient() {
if (httpClient == null) {
httpClient = newHttpClient();
httpClient = newBuilder().build();
}
return httpClient;
}
public static synchronized void reinit() {
httpClient = newHttpClient();
httpClient = newBuilder().build();
}
/**
@ -67,33 +72,33 @@ public class AntennapodHttpClient {
* @return http client
*/
@NonNull
public static OkHttpClient newHttpClient() {
public static OkHttpClient.Builder newBuilder() {
Log.d(TAG, "Creating new instance of HTTP client");
System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// detect 301 Moved permanently and 308 Permanent Redirect
client.networkInterceptors().add(chain -> {
builder.networkInterceptors().add(chain -> {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == HttpURLConnection.HTTP_MOVED_PERM ||
response.code() == StatusLine.HTTP_PERM_REDIRECT) {
String location = response.header("Location");
if (location.startsWith("/")) { // URL is not absolute, but relative
URL url = request.url();
location = url.getProtocol() + "://" + url.getHost() + location;
HttpUrl url = request.url();
location = url.scheme() + "://" + url.host() + location;
} else if (!location.toLowerCase().startsWith("http://") &&
!location.toLowerCase().startsWith("https://")) {
// Reference is relative to current path
URL url = request.url();
String path = url.getPath();
HttpUrl url = request.url();
String path = url.encodedPath();
String newPath = path.substring(0, path.lastIndexOf("/") + 1) + location;
location = url.getProtocol() + "://" + url.getHost() + newPath;
location = url.scheme() + "://" + url.host() + newPath;
}
try {
DBWriter.updateFeedDownloadURL(request.urlString(), location).get();
DBWriter.updateFeedDownloadURL(request.url().toString(), location).get();
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
@ -104,26 +109,26 @@ public class AntennapodHttpClient {
// set cookie handler
CookieManager cm = new CookieManager();
cm.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
client.setCookieHandler(cm);
builder.cookieJar(new JavaNetCookieJar(cm));
// set timeouts
client.setConnectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
client.setReadTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
client.setWriteTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
// configure redirects
client.setFollowRedirects(true);
client.setFollowSslRedirects(true);
builder.followRedirects(true);
builder.followSslRedirects(true);
ProxyConfig config = UserPreferences.getProxyConfig();
if (config.type != Proxy.Type.DIRECT) {
int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
Proxy proxy = new Proxy(config.type, address);
client.setProxy(proxy);
builder.proxy(proxy);
if (!TextUtils.isEmpty(config.username)) {
String credentials = Credentials.basic(config.username, config.password);
client.interceptors().add(chain -> {
builder.interceptors().add(chain -> {
Request request = chain.request().newBuilder()
.header("Proxy-Authorization", credentials).build();
return chain.proceed(request);
@ -131,9 +136,9 @@ public class AntennapodHttpClient {
}
}
if(16 <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < 21) {
client.setSslSocketFactory(new CustomSslSocketFactory());
builder.sslSocketFactory(new CustomSslSocketFactory(), trustManager());
}
return client;
return builder;
}
/**
@ -146,6 +151,23 @@ public class AntennapodHttpClient {
}
}
private static X509TrustManager trustManager() {
try {
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));
}
return (X509TrustManager) trustManagers[0];
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
return null;
}
}
private static class CustomSslSocketFactory extends SSLSocketFactory {
private SSLSocketFactory factory;

View File

@ -2,21 +2,7 @@ package de.danoeh.antennapod.core.service.download;
import android.text.TextUtils;
import android.util.Log;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import de.danoeh.antennapod.core.ClientConfig;
import de.danoeh.antennapod.core.R;
import de.danoeh.antennapod.core.feed.FeedImage;
import de.danoeh.antennapod.core.feed.FeedMedia;
import de.danoeh.antennapod.core.util.DateUtils;
import de.danoeh.antennapod.core.util.DownloadError;
import de.danoeh.antennapod.core.util.StorageUtils;
import de.danoeh.antennapod.core.util.URIUtil;
import okio.ByteString;
import org.apache.commons.io.IOUtils;
import java.io.BufferedInputStream;
@ -32,6 +18,22 @@ import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Date;
import de.danoeh.antennapod.core.ClientConfig;
import de.danoeh.antennapod.core.R;
import de.danoeh.antennapod.core.feed.FeedImage;
import de.danoeh.antennapod.core.feed.FeedMedia;
import de.danoeh.antennapod.core.util.DateUtils;
import de.danoeh.antennapod.core.util.DownloadError;
import de.danoeh.antennapod.core.util.StorageUtils;
import de.danoeh.antennapod.core.util.URIUtil;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.ByteString;
public class HttpDownloader extends Downloader {
private static final String TAG = "HttpDownloader";
@ -57,8 +59,9 @@ public class HttpDownloader extends Downloader {
}
}
OkHttpClient httpClient = AntennapodHttpClient.newHttpClient();
httpClient.interceptors().add(new BasicAuthorizationInterceptor(request));
OkHttpClient.Builder httpClientBuilder = AntennapodHttpClient.newBuilder();
httpClientBuilder.interceptors().add(new BasicAuthorizationInterceptor(request));
OkHttpClient httpClient = httpClientBuilder.build();
RandomAccessFile out = null;
InputStream connection;
ResponseBody responseBody = null;
@ -103,7 +106,9 @@ public class HttpDownloader extends Downloader {
} catch (IOException e) {
Log.e(TAG, e.toString());
if (e.getMessage().contains("PROTOCOL_ERROR")) {
httpClient.setProtocols(Collections.singletonList(Protocol.HTTP_1_1));
httpClient = httpClient.newBuilder()
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build();
response = httpClient.newCall(httpReq.build()).execute();
} else {
throw e;

View File

@ -8,11 +8,6 @@ import android.net.wifi.WifiManager;
import android.support.v4.net.ConnectivityManagerCompat;
import android.text.TextUtils;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
@ -22,6 +17,9 @@ import de.danoeh.antennapod.core.feed.FeedMedia;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.service.download.AntennapodHttpClient;
import de.danoeh.antennapod.core.storage.DBWriter;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;