我正在使用
classpath 'com.android.tools.build:gradle:3.2.1'
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip
并且每次我尝试连接服务器API时都会超时。
HTTP失败:java.net.SocketTimeoutException
我的服务器API非常好,我已经用邮递员和直接URL测试了它。解决此问题的唯一方法是降级到3.0.4 gradle插件或将android设备连接到VPN。我来自伊朗,我怀疑我的国家/地区的服务器是否存在访问问题。我什至尝试为HTTPClient设置长超时,但是在每个单独的API上我仍然遇到相同的错误。但是,经过20-30次重试后,我最终只能收到1个成功的响应。
我正在使用Retrofit2。
我也尝试在清单中设置此设置,但未更改
android:usesCleartextTraffic="true"
还有其他人在为这个问题苦苦挣扎吗?有人有解决办法吗?
答案 0 :(得分:0)
我发现了问题!自签名SSL服务器存在问题。解决方法是: 您必须创建一个UnsafeClient类,然后将其设置为翻新的客户端。
public class UnsafeOkHttpClient {
public static OkHttpClient getUnsafeOkHttpClient() {
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();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
OkHttpClient okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("BASEURL")
.client(okHttpClient);