关于HttpUrlConnection加载和下载网络图片的学习

一、加载网络图片

1.首先在layout布局文件里创建Button和ImageView两个控件

<Button
        android:paddingTop="10dp"
        android:id="@+id/load_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加载图片"/>
    <ImageView
        android:id="@+id/load_img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

2.然后在MainActivity里定义这两个控件,同时绑定ID,设置监听事件

 private Button loadBtn;
    private ImageView loadImg;
 loadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
 private void bindID() {
        loadBtn=findViewById(R.id.load_btn);
        loadImg=findViewById(R.id.load_img);
    }

3.接下来就是最重要的,要定义一个方法,来进行传值

  private ImageView imageView;
public ImgLoadTask(ImageView iv) {
        this.imageView=iv;

4.再然后就是自己定义一个Task类来继承AsyncTask来实现doInBackground方法,在里面进行加载图片的操作

protected Bitmap doInBackground(String... strings) {
        //加载网络图片,最后获取一个Bitmap对象,返回Bitmap对象
          Bitmap bm = null;
        try {
            URL url=new URL(strings[0]);
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            bm = BitmapFactory.decodeStream(inputStream);//把输入流转换成Bitmap类型对象
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bm;
    }

5.最后就是回到MainActivity中的onClick方法里来启动这个Task类

ImgLoadTask task=new ImgLoadTask(loadImg);
             task.execute("http://pic.qqtn.com/up/2017-4/2017040711143664251.jpg");

注意点:execute里放的就是图片的地址,右击图片点击复制图片地址即可复制


二、下载网络图片

1.基于加载网络图片,在下载图片的layout布局上就引用它的,就不多加赘述了
2.然后就是在主体类里定义绑定控件,设置点击事件

private ImageView downImg;
    private Button downBtn;
 downBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
 private void bind() {
        downImg=findViewById(R.id.down_img);
        downBtn=findViewById(R.id.down_btn);
    }

3.接着就是创建一个Task类来继承AsyncTask方法,定义下载图片的目录和最终位置,这是很重要的

public class DownLoadTask extends AsyncTask<String, Integer, Integer> {
    private String dirpath;//下载图片的目录   例如/root/pic
    private String filepath;//下载图片存储的具体位置    例如/root/pic/a.jpg

4.再接着就是在doInBackground子线程方法里来进行目录和文件是否存在,不存在则创建的关键步骤

  String fileName=strings[1];//要存储图片的名字

        //判断目录是否存在,若不存在,创建目录
        dirpath=Environment.getExternalStorageDirectory()+"/download_pic/";

        File dir=new File(dirpath);//目录对象
        if(!dir.exists()){
            dir.mkdir();
        }
        //判断文件是否存在,若不存在,创建文件
        filepath=dirpath+fileName;
        File file=new File(filepath);//创建文件对象
        if(file.exists()){
            return -1;
        }else
            try {
                file.createNewFile();//不存在,就创建出这个文件
            } catch (IOException e) {
                e.printStackTrace();
            }

5.紧接着就是要在下载好的文件里来写东西了,这就要用到InputStream和OutputStream了,也就是要用到上节课学的HttpUrlConnection请求了

InputStream inputStream=null;
            OutputStream outputStream=null;

        try {
            URL url=new URL(strings[0]);
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            if(httpURLConnection.getResponseCode()==200){
                inputStream=httpURLConnection.getInputStream();
            }else {
                return -2;
            }
            outputStream=new FileOutputStream(file);

            int length=0;
            byte[] buffer=new byte[4*1024];
            while ((length=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,length);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 1;
    }

6.随后就是创一个onPostExecute方法要对 doInBackground方法的return来进行接受,最主要的就是对上面返回的三种情况下载情况进行switch判断

protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        switch (integer){
            case 1:
                //下载完成
                Toast.makeText(context,"下载完成",Toast.LENGTH_SHORT).show();
                Bitmap bm=BitmapFactory.decodeFile(filepath);
                downImg.setImageBitmap(bm);
                break;
            case -1:
                //文件已存在
                Toast.makeText(context,"文件已存在",Toast.LENGTH_SHORT).show();
                break;
            case -2:
                //网络异常
                Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
                break;
        }
    }

7.写到这里,大家应该会有疑问,即第六步的context和Bitmap大家写了会报错。这就要我们在开头写一个Task方法来对content和Imgview来进行定义和调用

private Context context;
    private ImageView downImg;

    public DownLoadTask(Context context,ImageView downImg){
        this.context=context;
        this.downImg=downImg;
    }

8.然后就是回到主体类里定义一个picurl把图片的网址写在里面,方便直接引用

 private String picurl="http://p0.so.qhimgs1.com/bdr/_240_/t01ba1d62428a6cedbc.jpg";

9.再然后就是在点击方法里启动先前创建的Task类,在里面填入数据

 DownLoadTask downLoadTask=new DownLoadTask(DownLoadActivity.this,downImg);
                        downLoadTask.execute(picurl,"cat3.jpg");

括号里的cat3.jpg就是图片名称,当我们运行一次之后会显示“文件已存在”那么只要直接把文件名改下就行了
10.最后就是因为要上网下载图片,所以会有权限的问题,而安卓6.0以下版本只需要在manifest文件里加以下两行代码就行了

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

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

而如果是6.0以上版本则可以参考3052world的“ Android6.0权限分配终极解决方案”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值