Okhttp從2.4升級(jí)到3.9.1對(duì)HTTPS認(rèn)證的影響
嚴(yán)格意義上講,本文不應(yīng)屬于這個(gè)系列,但由于前面兩篇博客的代碼是參考《Android Https相關(guān)完全解析 當(dāng)OkHttp遇到Https》改寫(xiě)的,當(dāng)時(shí)的okhttp框架的版本為2.4.0,但現(xiàn)在okhttp版本升級(jí)到了3.9.1,并且查了一下相關(guān)資料,發(fā)現(xiàn)okhttp從2.x到3.x版本的api變化比較大庙睡,因此我也嘗試著將okhttp版本進(jìn)行升級(jí),并做簡(jiǎn)要記錄與大家分享技俐。
1.1 okhttp Jar包升級(jí)
將compile 'com.squareup.okhttp:okhttp:2.4.0'
更新為compile 'com.squareup.okhttp3:okhttp:3.9.1'
乘陪,Android Studio會(huì)自動(dòng)下載3.9.1的okhttp jar包。
1.2 更新Api及修正相關(guān)編譯錯(cuò)誤
Rebuild project雕擂,會(huì)發(fā)現(xiàn)有許多錯(cuò)誤
1.2.1 包名更新
Okhttp2.x的包名為com.squareup.okhttp
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
但okhttp3.x已經(jīng)變?yōu)閛khttp3,如上面的包名則相對(duì)應(yīng)變?yōu)椋?/p>
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
1.2.2 OkHttpClient創(chuàng)建方式不同
okhttp2.x直接new OkHttpClient啡邑,而okhttp3.x 中提供了Builder,很好的使用了創(chuàng)建者設(shè)計(jì)模式
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
1.2.3 OkHttpClient參數(shù)的配置變化
之前okhttp2.x參數(shù)可以直接OkHttpClient.setConnectTimeout()設(shè)置井赌,現(xiàn)在OkHttpClient使用創(chuàng)建者模式谤逼,需要在OkHttpClient.Builder上設(shè)置可配置的參數(shù):
okHttpClient.connectTimeout(5, TimeUnit.SECONDS);
okHttpClient.readTimeout(5, TimeUnit.SECONDS);
1.2.4 setCookieHandler變?yōu)閏ookieJar
okhttp2.x調(diào)用OkHttpClient的setCookieHandler方法,CookieHandler 的子類(lèi)CookieManager實(shí)現(xiàn)了cookie的具體管理方法,
mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
okhttp3中已經(jīng)沒(méi)有setCookieHandler方法了仇穗,而改成了cookieJar流部,需要在OkHttpClient的Builder的cookieJar方法中設(shè)置。
okHttpClient.cookieJar(new CookieJar() {
private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url, cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
return null;
}
});
1.2.5 改造setSslSocketFactory
okhttp2.x的sslSocketFactory(SSLSocketFactory sslSocketFactory)已不推薦使用纹坐,取而代之的
public Builder sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
因此我們可以將其改造為
mOkHttpClient = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build();
trustManager是X509TrustManager 的一個(gè)實(shí)例
trustManager = trustManagerForCertificates(certificates);
private X509TrustManager trustManagerForCertificates(InputStream in)
throws GeneralSecurityException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
// Put the certificates a key store.
char[] password = "123456".toCharArray(); // Any password will work.
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
// Use it to build an X509 trust manager.
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
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];
}
所以
/******************************
* 單向認(rèn)證
******************************/
public void setOneWayCertificates(InputStream... certificates)
/******************************
* 雙向認(rèn)證
******************************/
public void setTwoWayCertificates(InputStream clientcertificates, InputStream... certificates)
可分別改造為:
/******************************
* 單向認(rèn)證
******************************/
public void setOneWayCertificates(InputStream certificates){
X509TrustManager trustManager;
try{
trustManager = trustManagerForCertificates(certificates);
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init(
null,
new TrustManager[] { trustManager },
new SecureRandom());
mOkHttpClient = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build();
} catch (Exception e){
Log.e("OkHttpClientManager", e.getMessage());
}
}
/******************************
* 雙向認(rèn)證
******************************/
public void setTwoWayCertificates(InputStream clientCertificates, InputStream certificates) {
X509TrustManager trustManager;
try {
trustManager = trustManagerForCertificates(certificates);
SSLContext sslContext = SSLContext.getInstance("TLS");
//初始化keystore
KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
clientKeyStore.load(clientCertificates, "123456".toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, "123456".toCharArray());
sslContext.init(
keyManagerFactory.getKeyManagers(),
new TrustManager[] { trustManager },
new SecureRandom());
mOkHttpClient = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
1.2.6 Callback實(shí)現(xiàn)的接口和call的變化
okhttp2.x的callback方法是void onFailure(Request request, IOException e);void onResponse(Response response) throws IOException;
okhttp3.x 的Callback方法為void onFailure(Call call, IOException e);void onResponse(Call call, Response response) throws IOException;
okhttp3對(duì)Call做了更簡(jiǎn)潔的封裝枝冀,okhttp3.x Call是個(gè)接口,okhttp的call是個(gè)普通class耘子,一定要注意果漾,無(wú)論哪個(gè)版本,call都不能執(zhí)行多次拴还,多次執(zhí)行需要重新創(chuàng)建跨晴。于是
private void deliveryResult(final ResultCallback callback, Request request) {
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
sendFailedStringCallback(request, e, callback);
}
@Override
public void onResponse(Response response) throws IOException {
try {
final String string = response.body().string();
if (callback.mType == String.class) {
sendSuccessResultCallback(string, callback);
} else {
Object o = mGson.fromJson(string, callback.mType);
sendSuccessResultCallback(o, callback);
}
} catch (IOException e) {
sendFailedStringCallback(response.request(), e, callback);
} catch (JsonParseException e) { //Json解析的錯(cuò)誤
sendFailedStringCallback(response.request(), e, callback);
}
}
});
}
就變?yōu)椋?/p>
private void deliveryResult(final ResultCallback callback, Request request) {
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(call.request(), e, callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
final String string = response.body().string();
if (callback.mType == String.class) {
sendSuccessResultCallback(string, callback);
} else {
Object o = mGson.fromJson(string, callback.mType);
sendSuccessResultCallback(o, callback);
}
} catch (IOException e) {
sendFailedStringCallback(response.request(), e, callback);
} catch (JsonParseException e) { //Json解析的錯(cuò)誤
sendFailedStringCallback(response.request(), e, callback);
}
}
});
}
至此欧聘,改造完畢片林,我們分驗(yàn)證單向認(rèn)證及雙向認(rèn)證均可得到如下log:
12-14 02:08:20.698 30391-30391/? D/MainActivity: Response is Hello world!
證明已可以正常通訊,說(shuō)明我們okhttp3.x版本升級(jí)成功怀骤。
參考:
- https://github.com/square/okhttp/blob/3f7a3344a4c85aa3bbb879dabac5ee625ab987f3/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java#L54
- okhttp3與舊版本okhttp的區(qū)別分析
- okhttp3 使用詳解及簡(jiǎn)單封裝
完整代碼可到我的github下載:
server: https://github.com/onroadtech/SpringbootBase/tree/springboot_https_self_signed_certificate_one_two_way_certificate
android:https://github.com/onroadtech/Android4HTTPS/tree/88aa11a9b224df1fd19a5120ff387e81dcd23867
本博文已同步發(fā)表于我的個(gè)人博客網(wǎng)站费封,歡迎轉(zhuǎn)載指正并注明出處。
個(gè)人博客: www.onroad.tech
指正郵箱: onroad_tech@163.com