Retrofit2使用https請求

 

由於項目上傳到GooglePlay時被提醒傳輸數據方式不安全,故改用https加密傳輸。這裏我的項目裏用到Retrofit2.2.0,但Retrofit本身的okhttp不能直接請求證書不安全的https,所以得采取一些應急措施。

首先我們在androidstudio裏的gradle依賴Retrofit,如下:

 

compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'

 

 

然後把生成的證書文件key放入項目目錄的raw文件夾下,沒有raw的話就新建一個即可,這裏key是bks後綴的,不是的話自行google如何轉換成bks。

 

這裏我們需添加一個新類,爲取得SSL一些實例:

 

public class SslContextFactory {
    private static final String CLIENT_TRUST_PASSWORD = "*******";//信任證書密碼
    private static final String CLIENT_AGREEMENT = "TLS";//使用協議
    private static final String CLIENT_TRUST_MANAGER = "X509";
    private static final String CLIENT_TRUST_KEYSTORE = "BKS";
    SSLContext sslContext = null;

    public SSLContext getSslSocket(Context context) {
        try {
//取得SSL的SSLContext實例
            sslContext = SSLContext.getInstance(CLIENT_AGREEMENT);
//取得TrustManagerFactory的X509密鑰管理器實例
            TrustManagerFactory trustManager = TrustManagerFactory.getInstance(CLIENT_TRUST_MANAGER);
//取得BKS密庫實例
            KeyStore tks = KeyStore.getInstance(CLIENT_TRUST_KEYSTORE);
            InputStream is = context.getResources().openRawResource(R.raw.key);
            try {
                tks.load(is, CLIENT_TRUST_PASSWORD.toCharArray());
            } finally {
                is.close();
            }
//初始化密鑰管理器
            trustManager.init(tks);
//初始化SSLContext
            sslContext.init(null, trustManager.getTrustManagers(), null);
        } catch (Exception e) {
            Log.e("SslContextFactory", e.getMessage());
        }
        return sslContext;
    }
}

 

 

有了這個類,我們就可以完成retrofit2對https的請求了,下面做出處理:

 

//retrofit2訪問https
        SSLSocketFactory sslSocketFactory = new SslContextFactory().getSslSocket(context).getSocketFactory();
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://test.pengfff/") //url自行配置
                .client(okHttpClient.build())
                .build();
        PostService postService = retrofit.create(PostService.class);
        Call<ResponseBody> call = postService.postFormUrlEncoded(name,pwd);
        call.enqueue(new Callback<ResponseBody>()

        {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String result = response.body().toString();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(mcontext, t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }


    public interface PostService {
        @POST("test")
        @FormUrlEncoded
        Call<ResponseBody> postFormUrlEncoded(@Field("name") String name, @Field("pwd") String pwd);
    }

 

這是一個很普通的POST表單請求,請求方式爲HTTPS

最後測試返回結果成功,大家有問題可以評論下面提問,謝謝。

 

尊重作者成果:https://blog.csdn.net/PengFFF/article/details/70682494

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章