hub*_*ert 23 ssl android http retrofit
我正在尝试使用Retrofit连接到android上的https服务器.这是我的OkHttpClient
@Provides
public OkHttpClient provideContactClient(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(CipherSuite.TLS_RSA_WITH_DES_CBC_SHA,
CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
SSLSocketFactory sslSocketFactory = null;
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
sslSocketFactory = sslContext.getSocketFactory();
}catch (GeneralSecurityException e){
e.printStackTrace();
}
return new OkHttpClient.Builder()
.addInterceptor(interceptor)
.connectionSpecs(Collections.singletonList(spec))
.sslSocketFactory(sslSocketFactory)
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
if(responseCount(response) >= 5){
return null;
}
String credential = Credentials.basic("user", "pass");
return response.request().newBuilder().header("Authorization", credential).build();
}
})
.build();
}
Run Code Online (Sandbox Code Playgroud)
但是我一直都是CLEARTEXT communication not supported:例外
在调试RealConnection类时,我注意到route.address()成员没有sslSocketFactory在Bulider中分配它.
Jit*_*iya 73
根据网络安全配置
本部分中的指南仅适用于针对Android 8.1(API级别27)或更低级别的应用.从Android 9(API级别28)开始,默认情况下禁用明文支持.
创建文件res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
</domain-config>
</network-security-config>
Run Code Online (Sandbox Code Playgroud)
AndroidManifest.xml中
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...>
...
</application>
</manifest>
Run Code Online (Sandbox Code Playgroud)
或者您可以直接在清单中设置应用程序.
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
Run Code Online (Sandbox Code Playgroud)
nut*_*ter 17
仅将此添加到清单(应用程序内部)
android:usesCleartextTraffic="true"
Run Code Online (Sandbox Code Playgroud)
作品!
CLEARTEXT消息归因于http直接或通过服务器端重定向(例如,以开头https,然后重定向至http)请求的URL 。
对于“未找到证书路径的信任锚”消息而言,您的服务器似乎正在使用某些SSL证书,该证书在任何要测试的Android环境上均不受标准证书之一的支持。例如,也许您的服务器使用的是自签名SSL证书。
选项包括:
在Android 7.0+上使用网络安全配置
在Android 4.2+上使用我的网络安全配置的反向端口
设置一个SSLContext了解您的自签名证书的证书,然后将该证书附加到OkHttp,如此OkHttp配方所示
| 归档时间: |
|
| 查看次数: |
20176 次 |
| 最近记录: |