app帶證書驗證的方法和okhttp日誌攔截器類

/**
 * app帶證書驗證的方法,使用是修改一下zhaoapi_server.cer即可,其他都是固定的模式,直接拷貝
 */
public OkHttpClient setCard(String zhenshu) {
    //修改
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    try {
        //tps固定模式,X.509是固定的模式
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        //關聯證書的對象
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        String certificateAlias = Integer.toString(0);
        //核心邏輯,信任什麼證書,從Assets讀取拷貝進去的證書
        keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(getAssets().open(zhenshu)));
        SSLContext sslContext = SSLContext.getInstance("TLS");
        //信任關聯器
        final TrustManagerFactory trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        //初始化證書對象
        trustManagerFactory.init(keyStore);
        sslContext.init
                (
                        null,
                        trustManagerFactory.getTrustManagers(),
                        new SecureRandom()
                );

        //修改
        builder.sslSocketFactory(sslContext.getSocketFactory());
        builder.addInterceptor(new LogInterceptor());
        //信任請求主機
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    return builder.build();
}
//okhttp日誌攔截器類
/**
 * okhttp日誌攔截器
 */
public class LogInterceptor implements Interceptor {

    public static String TAG = "LogInterceptor";

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration=endTime-startTime;
        MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Log.d(TAG,"\n");
        Log.d(TAG,"----------Start----------------");
        Log.d(TAG, "| "+request.toString());
        String method=request.method();
        if("POST".equals(method)){
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
                Log.d(TAG, "| RequestParams:{"+sb.toString()+"}");
            }
        }
        Log.d(TAG, "| Response:" + content);
        Log.d(TAG,"----------End:"+duration+"毫秒----------");
        return response.newBuilder()
                .body(ResponseBody.create(mediaType, content))
                .build();
    }

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