1. 程式人生 > >https請求資料,ca機構安全證書

https請求資料,ca機構安全證書

有兩種方法請求引數,一種是信任所有https的請求,一種是帶證書的驗證並請求
首先寫bean類,之後需要寫攔截器,這個類可以直接複製
public class LogInterceptor implements Interceptor {

    public static String TAG = "LogInterceptor";

    @Override
    public Response intercept(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(); } }

不要忘記寫聯網許可權和寫入SD卡的許可權
之後在MainActivity類中的onCreate()方法裡面寫
// loadData();//信任所有https的請求:第一種實現
  cardData();//帶證書驗證
在方法外面寫這兩個方法,缺啥補啥,已經註釋了,這是兩種方法來請求資料。一定要看清註解
/**
 * 帶證書驗證
 */
private void cardData() {

    FormBody formbody = new FormBody.Builder().add("mobile", "13717830672").add("password", "123456").build();
    Request request = new Request.Builder().url("https://www.zhaoapi.cn/user/login").post(formbody).build();

    //帶證書驗證裡的方法
    setCard().newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful() && response != null && response.body() != null){
                final String result;
                try {
                    result = response.body().string();
                    Gson gson = new Gson();
                    Bean bean = gson.fromJson(result, Bean.class);
                    Bean.DataBean data = bean.getData();
                    String mobile = data.getMobile();
                    System.out.println("登入的手機號mobile = " + mobile);


                }catch (Exception e){

                }
            }
        }
    });

}

//帶證書驗證裡的方法
public OkHttpClient setCard() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        String certificateAlias = Integer.toString(0);
        keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(getAssets().open("zhaoapi_server.cer")));//拷貝好的證書
        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();
}


/**
 * 信任所有https的請求:第一種實現
 */
private void loadData() {
    OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new LogInterceptor())//攔截器
            .sslSocketFactory(createSSLSocketFactory()).hostnameVerifier(new TrustAllHostnameVerifier())
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(false)
            .build();

    FormBody formbody = new FormBody.Builder().add("mobile", "13717830672").add("password", "123456").build();
    Request request = new Request.Builder().url("https://120.27.23.105/user/login").post(formbody).build();
    httpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful() && response != null && response.body() != null){
                final String result;
                try {
                    result = response.body().string();
                    Gson gson = new Gson();
                    Bean bean = gson.fromJson(result, Bean.class);
                    Bean.DataBean data = bean.getData();
                    String mobile = data.getMobile();
                    System.out.println("登入的手機號mobile = " + mobile);


                }catch (Exception e){

                }
            }
        }
    });
}

//信任所有https的請求的方法
private static SSLSocketFactory createSSLSocketFactory() {
    SSLSocketFactory ssfFactory = null;

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

        ssfFactory = sc.getSocketFactory();
    } catch (Exception e) {
    }

    return ssfFactory;
}

//信任所有https的請求的方法
private static class TrustAllCerts implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

//信任所有https的請求的方法
private static class TrustAllHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

如果是帶證書的驗證,需要在main檔案下建立asstes,然後將ca證書複製到裡面。