欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用HttpURLConnection加载网络图片

程序员文章站 2022-07-01 20:30:15
...

加载网络图片,需要用到Bitmap对象。
加载网络图片有时也需耗时较长时间,所以也应该异步加载。
在此,以AsyncTask为例。
首先 写在前面:
android使用网络一定记得加上网络访问权限

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

示例图:

使用HttpURLConnection加载网络图片
xml中代码如下:

<?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="com.example.administrator.myapplication.MainActivity">
    <android.support.v7.widget.AppCompatSeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bar"
        style="?android:attr/progressBarStyleHorizontal"
        />
    <Button

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载"
        android:id="@+id/btn0"

        />
<ImageView
    android:id="@+id/imageview"
    android:scaleType="fitCenter"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>

AsyncTask代码如下:

package com.example.administrator.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Administrator on 2018/3/13/013.
 */

public class DownloadTask extends AsyncTask<String,Integer,Integer> {
    private Button button;
    private SeekBar bar;
    private ImageView imageView;
    private Context context;
    //**********文件相关变量
    private String SDPATH = "";
    private String PATH="";
    private String fileName;

    public  DownloadTask(Context context, Button button, SeekBar bar, ImageView imageView){
        this.context=context;
        this.button=button;
        this.imageView=imageView;
        this.bar=bar;
        this.SDPATH = Environment.getExternalStorageDirectory() + "/";
        // Environment.getExternalStorageDirectory() 这个方法,获取目录
        this.PATH = this.SDPATH+"download_pic/";
        System.out.println("PATH***:"+PATH);
    }

    @Override
    protected Integer doInBackground(String... strings) {
        InputStream inputStream=null;
        OutputStream outputStream=null;
        File file=null;
        fileName=PATH+strings[1];
        if (isFileExists(PATH+strings[1])){
            return 1;
        }
        try {
            //创建URL
            URL url=new URL(strings[0]);
            //通过HttpURLConnection创建网页请求
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            //判断请求是否成功
            if (httpURLConnection.getResponseCode()==200){
                inputStream=httpURLConnection.getInputStream();
                publishProgress(-2,httpURLConnection.getResponseCode());
            }
            else {
                publishProgress(-1);
            }
            //创建文件目录
            createDir(PATH);
            //创建文件
            file= creatFile(PATH+strings[1]);
            //创建输出流
            outputStream=new FileOutputStream(file);
            //创建缓冲区
            byte buffer[]=new byte[4*1024];
            int lenth=0;
            int sum=0;
            while ((lenth=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,lenth);
                //
                sum+=lenth;
                //
                publishProgress(0,sum);

            }
            outputStream.flush();


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

        return 0;
    }

    private File creatFile(String s) {
        File file=new File(s);
        boolean isCreatFile=false;
        try {
            isCreatFile=file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        switch (values[0]){
            case 0:
                bar.setProgress(values[1]);
                break;
            case -1:
                bar.setProgress(values[1]);
                Toast.makeText(context, "网络连接错误,请检查下载链接是否正确", Toast.LENGTH_LONG).show();
                break;
            case -2:
                bar.setMax(values[1]);
                break;
            default:
                break;
        }
    }


    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        button.setEnabled(true);
        switch (integer) {
            case 1:
                Toast.makeText(context, "文件已存在", Toast.LENGTH_LONG).show();
                break;
            case 0:
                Bitmap bitmap= BitmapFactory.decodeFile(fileName);
                imageView.setImageBitmap(bitmap);
                Log.e("Task","下载完成");

            default:
                break;
        }

    }


    private boolean createDir(String path) {
        File file=new File(path);
        boolean iscreateDir=file.mkdir();
        return  iscreateDir;
    }

    public boolean isFileExists(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            // 文件已存在
            return true;
        }
        return false;

    }


}

mainactivity中代码:

package com.example.administrator.myapplication;

import android.Manifest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import com.master.permissionhelper.PermissionHelper;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;



    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
        private Button button;
        private SeekBar bar;
        private ImageView imageView;
        private String TAG = "HelloActivity";
        private PermissionHelper permissionHelper;



        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            BlindID();
            //关于权限代码
            permissionHelper = new PermissionHelper(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            permissionHelper.request(new PermissionHelper.PermissionCallback(){

                @Override
                public void onPermissionGranted() {
                    //全都授权
                    Log.e(TAG,"onPermissionGranted...");

                }

                @Override
                public void onIndividualPermissionGranted(String[] grantedPermission) {
                    Log.e(TAG,"onIndividualPermissionGranted...");
                }

                @Override
                public void onPermissionDenied() {
                    Log.e(TAG,"onPermissionDenied...");
                }

                @Override
                public void onPermissionDeniedBySystem() {
                    Log.e(TAG,"onPermissionDeniedBySystem...");
                }
            });
        }

        private void BlindID() {
            button=findViewById(R.id.btn0);
            imageView=findViewById(R.id.imageview);
            bar=findViewById(R.id.bar);
            button.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btn0:
                    button.setEnabled(false);
                    DownloadTask dowland=new DownloadTask(MainActivity.this,button,bar,imageView);
                    dowland.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg","wqca.jpg");
                    break;
            }
        }
    }
相关标签: 哈哈哈