1. 代码
private static final String PATH = "https://i1.hdslb.com/bfs/face/56076ccc641c93a69fbe2b4e7a29a6d3992873da.jpg@240w_240h_1c_1s.webp";
private static final String TAG = "MainActivity";
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.iv);
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().get().url(PATH).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.e(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
});
}
2. 可能遇到的问题
2.1 问题一
java onFailure: java.io.IOException: canceled due to java.lang.SecurityException: Permission denied (missing INTERNET permission?)
解决:很明显,没有网络权限,在AndroidManifest.xml文件中添加
<uses-permission android:name="android.permission.INTERNET" />
2.2 问题二
onFailure: java.net.SocketException: socket failed: EPERM (Operation not permitted)
在添加了网络权限再次运行后仍然报错,这个时候将应用卸载了重新安装即可。
如果是http请求,记得在AndroidManifest.xml文件中添加
android:usesCleartextTraffic="true"