Android使用HttpClient下載圖片

dwd4 9年前發布 | 2K 次閱讀 Java Android

HttpURLConnection與HttpClient的區別:

HttpClient是個很不錯的開源框架(org.appache.http),封裝了訪問http的請求頭,參數,內容體,響應等等,使用起來更方面更強大。
HttpURLConnection是java的標準類,可以實現簡單的基于URL請求、響應功能,什么都沒封裝,用起來太原始,比如重訪問的自定義,以及一些高級功能等。

還是在上一章的基礎上添加HttpClient

/**
     * 通過Get獲取網頁內容
     * 
     * @param url
     *            如:http://preview.quanjing.com/is002/ev601-025.jpg
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @date 2014.05.10
     */
    public static Bitmap getHttpGetBitmap(String url)
            throws ClientProtocolException, IOException {
        Bitmap bitmap = null;
        // 新建一個默認的連接
        HttpClient client = new DefaultHttpClient();
        // 新建一個Get方法
        HttpGet get = new HttpGet(url);
        // 得到網絡的回應
        HttpResponse response = client.execute(get);

        // 如果服務器響應的是OK的話!
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        }
        return bitmap;
    }

訪問互聯網權限

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

Activity下載代碼

package com.dzt.downloadimage;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.dzt.downloadimage.utils.HttpUtils;

public class MainActivity extends Activity implements OnClickListener {

    private Bitmap mDownloadImage = null;
    private ImageView image = null;
    private downloadImageTask task;
    private boolean _isExe = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWidgets();
        task = new downloadImageTask();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if (_isExe) {
            task.cancel(true); // 取消操作
        }
    }

    private void initWidgets() {
        image = (ImageView) findViewById(R.id.img);
        Button btn = (Button) findViewById(R.id.download_btn);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.download_btn:
            if (!_isExe) {
                task.execute("http://preview.quanjing.com/is002/ev601-025.jpg"); // 執行異步操作
                _isExe = true;
            }
            break;

        default:
            break;
        }
    }

    class downloadImageTask extends AsyncTask<String, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            System.out.println("[downloadImageTask->]doInBackground "
                    + params[0]);
            // try {
            // mDownloadImage = HttpUtils.getNetWorkBitmap(params[0]);
            // } catch (MalformedURLException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // } catch (IOException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            try {
                mDownloadImage = HttpUtils.getHttpGetBitmap(params[0]);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return true;
        }

        // 下載完成回調
        @Override
        protected void onPostExecute(Boolean result) {
            // TODO Auto-generated method stub
            image.setImageBitmap(mDownloadImage);
            System.out.println("result = " + result);
            super.onPostExecute(result);
        }

        // 更新進度回調
        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }

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