1. 程式人生 > >Retrofit2對https請求的實現(乾貨)

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

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