我有一些网址图片,但有些图片没有显示,并为 Picasso 或 Glide 提供错误下载..但是设备 API 19的错误或以下 for API 24下载没有问题,如下面的图片
代码中的相同网址但未在右侧设备中显示(API 19),但在左侧显示(API24):
我的代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
String url = "https://vid.alarabiya.net/images/2018/02/28/56cd42cd-c24e-473c-9701-2c361fdb92e8/56cd42cd-c24e-473c-9701-2c361fdb92e8_16x9_1200x676.JPG";
Glide.with(this).load(url).into(imageView);
}
}
答案 0 :(得分:0)
这是一个已知问题。这与okhttp无法在Android 4.1-4.4上启用TLSv1.2有关。
请点击此处https://github.com/square/okhttp/issues/2372以便更好地理解。
这是您的答案:您必须添加自定义GlideModule和两个依赖项
的build.gradle
implementation 'com.github.bumptech.glide:glide:4.6.1'
compile "com.github.bumptech.glide:okhttp3-integration:4.6.1"
compile 'com.github.bumptech.glide:annotations:4.6.1'
CustomGlideModule
import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.AppGlideModule;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.TlsVersion;
@GlideModule
public class CustomGlideModule extends AppGlideModule {
@Override
public void registerComponents(Context context, Glide glide, Registry registry) {
OkHttpClient client = getNewHttpClient();
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(client));
}
private OkHttpClient getNewHttpClient() {
OkHttpClient.Builder client = new OkHttpClient.Builder()
.followRedirects(true)
.followSslRedirects(true)
.retryOnConnectionFailure(true)
.cache(null)
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS);
return enableTls12OnPreLollipop(client).build();
}
public static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {
if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);
client.connectionSpecs(specs);
} catch (Exception exc) {
Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc);
}
}
return client;
}
}
我已经过测试,它在API 19上运行。
希望这有帮助。