OkHttp的简单使用(下载图片),结合Glide显示图片

本文介绍了如何使用OkHttp下载图片,并结合Glide进行显示。首先讲解了OkHttp的导入、主要类及其用法,包括Http协议注意事项。接着详细阐述了Glide的导入和多种用法,如加载网络、本地和资源ID图片。提供了完整的代码示例,演示了从下载到显示的整个流程,强调直接使用Glide显示图片的便利性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先使用OkHttp把图片下载下来,再使用Glide显示图片。效果展示在最后面

一、OkHttp

1.OkHttp的导入

在Moudle的gradle中添加

implementation("com.squareup.okhttp3:okhttp:4.2.0")
2.OkHttp的主要类

在这里插入图片描述

  • OkHttpClient(请求客户端)
    它的主要目的就是用来创建Call对象的,而这个Call对象是用来发起HTTP请求和读取返回结果的。
  • Request
    包装的一个HTTP请求
  • Call
    通过该类真正发起请求,取消请求,并且可以判断当前请求的状态。
  • RequestBody
    请求体
  • Response
    该类和Request构成了HTTP请求中的请求和响应。
3.关于Http协议

如果你用的是http访问网络,会报错。现在Android P全面禁止了非https链接(参考文章
但是国内的很多网站都是非https的,怎么办呢?需要使用xml文件设置属性禁用掉这一设置,在res文件夹下新建目录xml,然后创建文件network_security_config.xml(文件名随意):

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

然后在AndroidManifest.xml文件的Application标签添加属性:

<application
        ...
        android:networkSecurityConfig="@xml/network_security_config">
</application>

问题解决

4.简单案例

下载相关代码:

private void download() {
  String url="https://sf6-ttcdn-tos.pstatp.com/img/ee-finolhu/034e2e9d3cfe49f8bb0a3367c9afec47~noop.image";
 		//1.创建OkHttpClient对象
        OkHttpClient client=new OkHttpClient();
        //2.创建请求对象Request
        Request request=new Request.Builder()
                .url(url)
                .build();
         //3.执行请求
        Call call = client.newCall(request);
        //同步请求
        //Response response = call.execute();
        //执行异步请求的方式
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("onResponse", "onFailure: ");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                if (response.body().contentLength()>0){
                    InputStream is=response.body().byteStream();
                    File file=new File(Environment.getExternalStorageDirectory()+File.separator+BuildConfig.APPLICATION_ID+File.separator+"images");
                    Log.d("OkHttpTest", "onResponse: "+file.toString());
                    if (file.getParentFile().exists()){
                        try {
                            FileOutputStream fos=new FileOutputStream(file);
                            int len;
                            while ((len=is.read())!=-1){
                                fos.write(len);
                            }
                        } catch (FileNotFoundException e) {
                            Log.d("OkHttpTest", "FileNotFoundException: 异常了");
                            e.printStackTrace();
                        } catch (IOException e) {
                            Log.d("OkHttpTest", "IOException:异常了 ");
                            e.printStackTrace();
                        }
                    }else {
                        file.getParentFile().mkdirs();
                    }
                }else {
                    Toast.makeText(MainActivity.this, "访问的文件不存在", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

这个url是一张图片的网址,下载完成后在打印出来的文件路径下可以看到。在这里插入图片描述
先看看图长啥样:传送门

二、Glide的简单使用

1.Glide导入

在Moudle的gradle中添加:

  implementation 'com.github.bumptech.glide:glide:4.10.0'
2.Glide的几种用法
  • 加载网络图片
Glide.with(context).load(url).into(ImageView);
  • 加载本地图片
File file=new File(Environment.getExternalStorageDirectory()+File.separator+BuildConfig.APPLICATION_ID+File.separator+"images");
Glide.with(context).load(file).into(ImageView);
  • 加载资源id图片
int resourceId = R.mipmap.ic_launcher;
Glide.with(context).load(resourceId).into(ImageView);
  • 加载Gif图片
String url = "xxxxx";
Glide.with( context ).load( url ).into( ImageView);
  • 设置默认占位图.placeholder()
  • 设置加载失败的图片.error()
Glide.with( context ).load(url ).placeholder( R.drawable.xxx).error( R.drawable.xxx).into( ImageView);

三、完整代码

加权限

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载" />

    <Button
        android:id="@+id/button_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="展示" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btn_download;
    Button btn_show;
    ImageView iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_download=findViewById(R.id.button_download);
        btn_show=findViewById(R.id.button_show);
        iv=findViewById(R.id.iv);
        btn_show.setOnClickListener(this);
        btn_download.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button_download:
                Log.d("onResponse", "onClick: 我单击了");
                download();
                break;
            case R.id.button_show:
                show();
                break;
        }
    }

    private void show() {
        File file=new File(Environment.getExternalStorageDirectory()+File.separator+BuildConfig.APPLICATION_ID+File.separator+"images");
        Glide.with(MainActivity.this).load(file).into(iv);
    }

    private void download() {
        String url="https://sf6-ttcdn-tos.pstatp.com/img/ee-finolhu/034e2e9d3cfe49f8bb0a3367c9afec47~noop.image";
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("onResponse", "onFailure: ");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                if (response.body().contentLength()>0){
                    InputStream is=response.body().byteStream();
                    File file=new File(Environment.getExternalStorageDirectory()+File.separator+BuildConfig.APPLICATION_ID+File.separator+"images");
                    Log.d("OkHttpTest", "onResponse: "+file.toString());
                    if (file.getParentFile().exists()){
                        try {
                            FileOutputStream fos=new FileOutputStream(file);
                            int len;
                            while ((len=is.read())!=-1){
                                fos.write(len);
                            }
                        } catch (FileNotFoundException e) {
                            Log.d("OkHttpTest", "FileNotFoundException: 异常了");
                            e.printStackTrace();
                        } catch (IOException e) {
                            Log.d("OkHttpTest", "IOException:异常了 ");
                            e.printStackTrace();
                        }
                    }else {
                        file.getParentFile().mkdirs();
                    }
                }else {
                    Toast.makeText(MainActivity.this, "访问的文件不存在", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

效果展示:
在这里插入图片描述

后话

显示图片直接使用Glide就行了。没必要先下载。
修改上面的show()方法

 private void show() {
        String url="https://sf6-ttcdn-tos.pstatp.com/img/ee-finolhu/034e2e9d3cfe49f8bb0a3367c9afec47~noop.image";
        Glide.with(MainActivity.this).load(url).into(iv);
    }

可以直接显示图片。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值