In several case, you must be face a difficulty in Retrofit 1.7 how to add file certificate to Retrofit 1.7, right?
Because of this, i create this article and share my experience when i add file certificate to my apps using Retrofit 1.7
If you using Retrofit 1.7, make sure another support libraries are added, these libraries that i meant are :
compile 'com.squareup.okhttp:okhttp:2.0.0' compile 'com.squareup.okio:okio:1.13.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
After that, write to the following code in your apps to adding file certificate to Retrofit 1.7 :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Certificate ca = null; | |
OkHttpClient okHttpClient = new OkHttpClient(); | |
try { | |
CertificateFactory cf = CertificateFactory.getInstance("X.509"); | |
InputStream caInput = getApplicationContext().getResources().openRawResource(R.raw.your_file_cert); | |
try { | |
ca = cf.generateCertificate(caInput); | |
if(BuildConfig.DEBUG){ | |
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); | |
} | |
} finally { | |
caInput.close(); | |
} | |
} catch (Exception ex) { | |
if(BuildConfig.DEBUG){ | |
Log.e("MEH", "Unable to load the certificate: " + ex.getMessage()); | |
} | |
} | |
try { | |
String keyStoreType = KeyStore.getDefaultType(); | |
KeyStore keyStore = KeyStore.getInstance(keyStoreType); | |
keyStore.load(null, null); | |
keyStore.setCertificateEntry("ca", ca); | |
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); | |
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); | |
tmf.init(keyStore); | |
SSLContext sslContext = SSLContext.getInstance("SSL"); | |
sslContext.init( null, tmf.getTrustManagers(), null ); | |
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory()); | |
} catch ( Exception ex ) { | |
if(BuildConfig.DEBUG){ | |
Log.e("Log", "Unable to create the trust manager: " + ex.getMessage() ); | |
} | |
} | |
RestAdapter.Builder builder = new RestAdapter.Builder(); | |
builder.setEndpoint(Config.getUrl()); | |
if (!BuildConfig.DEBUG) { | |
builder.setClient(new OkClient(okHttpClient)); | |
} | |
builder.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE); | |
builder.setLog(new AndroidLog("Log File : ")); |
That's all about how to adding file Certificate to Retrofit 1.7, hope it helps and works in your project. Thank you.
EmoticonEmoticon