首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Retrofit 2获取SSLException

使用Retrofit 2获取SSLException
EN

Stack Overflow用户
提问于 2018-03-19 08:54:09
回答 2查看 1.7K关注 0票数 5

我正在创建授权应用程序,在其中我使用Retrofit 2。

"javax.net.ssl.SSLException: Connection closed by peer"

但问题是,昨天的情况很好。今天,它给出了例外。我在互联网上发现了一些SSLException -Android4.x版本上的对等程序关闭连接,或者如何在修改后添加TLS v1.0和TLS v.1.1,但这对我没有帮助。有什么办法解决它吗。在后端,启用TLS1.2。

代码语言:javascript
复制
public class RegistrationFragment extends BaseFragment {
View mainView;

ApiClient apiClient = ApiClient.getInstance();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainView = inflater.inflate
            (R.layout.registration_fragment, container, false);

            //Calling the authorization method
            registerCall();
        }
    });

    return mainView;
}

//User authorization method

public void registerCall() {

    Call<ResponseBody> call = apiClient.registration(supportopObj);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {

                //Calling the clientCall method for getting the user clientID and clientSecret
                Toast.makeText(getActivity(), "Registration Successful ",
                        Toast.LENGTH_SHORT).show();;

            } else {
                //if the response not successful
                Toast.makeText(getActivity(), "Could not register the user maybe already registered ",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "An error occurred", Toast.LENGTH_SHORT).show();
        }
    });
}
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-19 10:14:38

我在我的OkHttp初始化类中使用了类似的东西,但是在这里使用安全吗?

我创建了一个新的类Tls12SocketFactory.class

就在这里。

代码语言:javascript
复制
public class Tls12SocketFactory extends SSLSocketFactory {
private static final String[] TLS_V12_ONLY = {"TLSv1.2"};

final SSLSocketFactory delegate;

public Tls12SocketFactory(SSLSocketFactory base) {
    this.delegate = base;
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return patch(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return patch(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return patch(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return patch(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return patch(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket patch(Socket s) {
    if (s instanceof SSLSocket) {
        ((SSLSocket) s).setEnabledProtocols(TLS_V12_ONLY);
    }
    return s;
}
}

我在OkHttp初始化类中做了类似的事情。

代码语言:javascript
复制
X509TrustManager trustManager = null;

    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
         trustManager = (X509TrustManager) trustManagers[0];
    } catch (KeyStoreException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    OkHttpClient.Builder client = new OkHttpClient.Builder()
            .readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS);

    try {
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, new TrustManager[] { trustManager }, null);
        client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()), trustManager);
        ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .build();
        client.connectionSpecs(Collections.singletonList(cs));
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

 name = new Retrofit.Builder()
            .baseUrl(endpoint)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

所以在Android演播室中使用这段代码安全吗?而ш在未来的代码中会出现什么问题?谢谢。我想我的答案也能帮到其他人。

票数 0
EN

Stack Overflow用户

发布于 2018-03-19 09:05:28

这并不是因为重新装修,而是因为okhttp。如果您使用okhttp版本3.x,您将遇到这个问题。当前的解决方案是使用okHTTPVersion2.x。还有一件事要补充的是,这个问题只发生在Android版本16-20 链接以供参考上。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49358946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档