使用HttpURLConnection實現圖片的下載與現顯示

jopen 9年前發布 | 8K 次閱讀 Java Android

雖然我們在開發中經常使用別人已經開發好的開源框架,但是,了解這些框架底層的實現,能夠讓我們更好的理解功能的實現。

這篇文章主要介紹使用HttpURLConnection對象,實現圖片文件的下載,以及顯示。

我們的思路是,首先使用HttpURLConnection實現圖片文件的下載,在下載結束之后,使用handler異步的顯示圖片。

public class MainActivity extends Activity {  

    private Context mContext;  
    private ImageView image;  
    // 加載成功  
    private static final int LOAD_SUCCESS = 1;  
    // 加載失敗  
    private static final int LOAD_ERROR = -1;  
    // 用于異步的顯示圖片  
    private Handler handler = new Handler() {  
        public void handleMessage(Message msg) {  

            switch (msg.what) {  
            //下載成功  
            case LOAD_SUCCESS:  
                // 獲取圖片的文件對象  
                File file = new File(Environment.getExternalStorageDirectory(), "pic.jpg");  
                FileInputStream fis = null;  
                try {  
                    fis = new FileInputStream(file);  
                    Bitmap bitmap = BitmapFactory.decodeStream(fis);  
                    image.setImageBitmap(bitmap);  

                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                }  

                break;  
                //下載失敗  
            case LOAD_ERROR:  

                Toast.makeText(mContext, "加載失敗", 0).show();  

                break;  
            }  

        };  
    };  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        mContext = this;  
        setContentView(R.layout.activity_main);  
        image = (ImageView) findViewById(R.id.image);  
    }  

    // Button的點擊事件  
    public void show(View view) {  
        // 開啟新的線程用于下載圖片  
        new Thread(new Runnable() {  
            public void run() {  

                getPicture();  
            }  
        }).start();  

    }  

    //下載圖片的主方法  
    private void getPicture() {  

        URL url = null;  
        InputStream is = null;  
        FileOutputStream fos = null;  
        try {  
            //構建圖片的url地址  
            url = new URL("http://avatar.csdn.net/C/6/8/1_bz419927089.jpg");  
            //開啟連接  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            //設置超時的時間,5000毫秒即5秒  
            conn.setConnectTimeout(5000);  
            //設置獲取圖片的方式為GET  
            conn.setRequestMethod("GET");  
            //響應碼為200,則訪問成功  
            if (conn.getResponseCode() == 200) {  
                //獲取連接的輸入流,這個輸入流就是圖片的輸入流  
                is = conn.getInputStream();  
                //構建一個file對象用于存儲圖片  
                File file = new File(Environment.getExternalStorageDirectory(), "pic.jpg");  
                fos = new FileOutputStream(file);  
                int len = 0;  
                byte[] buffer = new byte[1024];  
                //將輸入流寫入到我們定義好的文件中  
                while ((len = is.read(buffer)) != -1) {  
                    fos.write(buffer, 0, len);  
                }  
                //將緩沖刷入文件  
                fos.flush();  
                //告訴handler,圖片已經下載成功  
                handler.sendEmptyMessage(LOAD_SUCCESS);  
            }  
        } catch (Exception e) {  
            //告訴handler,圖片已經下載失敗  
            handler.sendEmptyMessage(LOAD_ERROR);  
            e.printStackTrace();  
        } finally {  
            //在最后,將各種流關閉  
            try {  
                if (is != null) {  
                    is.close();  
                }  
                if (fos != null) {  
                    fos.close();  
                }  
            } catch (Exception e) {  
                handler.sendEmptyMessage(LOAD_ERROR);  
                e.printStackTrace();  
            }  
        }  
    }  

}  


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!