HTTPS/2017-12-28

添加okhttp的依赖

compile'com.squareup.okhttp3:okhttp:3.4.2'

创建一个日志拦截器

public class LogInterceptorimplements Interceptor {

public static StringTAG ="LogInterceptor";

    @Override

    public Responseintercept(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();

    }

}

在activity中进行网络请求

public class MainActivityextends AppCompatActivity {

@Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        cardData();

    }

/**

    * 带证书验证

    */

    private void cardData() {

//提交表单信息

        FormBody formbody =new FormBody.Builder().add("mobile", "18612991023").add("password", "111111").build();

        //请求对象初始化的设置,请求Url,请求方式,表单信息

        Request request =new Request.Builder().url("https://www.zhaoapi.cn/user/login").post(formbody).build();

        //setCard(),用时直接拷贝,app带证书验证

        setCard("zhaoapi_server.cer").newCall(request).enqueue(new Callback() {

@Override

            public void onFailure(Call call, IOException e) {

}

@Override

            public void onResponse(Call call, Response response)throws IOException {

}

});

    }

/**

    * app带证书验证的方法,使用是修改一下zhaoapi_server.cer即可,其他都是固定的模式,直接拷贝

    */

    public OkHttpClientsetCard(String zhenshu) {

OkHttpClient.Builder builder =new OkHttpClient.Builder();

        try {

//https固定模式,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();

    }

}

推荐阅读更多精彩内容