Reputation: 67
To communicate with back from my android app I use network-security-config.xml, which looks like
<network-security-config>
<base-config>
<trust-anchors>
<certificates src="@raw/my_ca"/>
<certificates src="system"/>
</trust-anchors>
</base-config>
</network-security-config>
where is my_ca - certificate (.pem file)
On API < 24 it's not working, how to solve this?
Upvotes: 2
Views: 2538
Reputation: 17755
The declarative network security configuration was added in Android 7 (API 24). Before that you have to do it programatically. Unfortunately it is not straightforward, the steps are :
KeyStore
X509TrustManager
SSLSocketFactory
OkHttpClient
Retrofit
builderThere is OkHttp recipe describing this.
It seems that there also is an OkHttp extension with a much simpler API :
val certificate = """-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE
""".decodeCertificatePem()
val certificates: HandshakeCertificates = HandshakeCertificates.Builder()
.addTrustedCertificate(certificate)
.addPlatformTrustedCertificates()
.build()
val client = OkHttpClient.Builder()
.sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager)
.build()
Retrofit.Builder()
.client(client)
...
.build()
.create(MyWebService::class.java)
A similar sample in java building the OkHttp client
Upvotes: 4