在android中的改造库中需要授权

时间:2017-03-01 10:20:14

标签: android android-studio ssl ssl-certificate retrofit2

我正在使用retrofit2库进行API调用。我的baseURl在 https ,即我使用自签名证书。所以我使用trustmanager信任所有证书并绕过android中的证书。以下是代码。

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
      try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

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

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


            httpClient.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
            httpClient.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

以下是我对改造的呼吁。

OkHttpClient okHttpClient = httpClient.build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Utils.URL_SERVER_ADDRESS_LATEST)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

但在完成上述所有过程后,我得到了以下回复

  

响应{protocol = http / 1.1,代码= 401,消息=需要授权,url = https://testapi.trick.net/api/login}

我希望有这样的解决方案,因为我过去两天一直在尝试。任何帮助将不胜感激。

0 个答案:

没有答案