Android採用HttpClient下載圖片

來源:互聯網
上載者:User

標籤:

在上一章中談到Android採用HttpURLConnection下載圖片,本章使用HttpClient下載圖片

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);// 假設server響應的是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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initWidgets();task = new downloadImageTask();}@Overrideprotected void onStop() {// TODO Auto-generated method stubsuper.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);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (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> {@Overrideprotected Boolean doInBackground(String... params) {// TODO Auto-generated method stubSystem.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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return true;}// 下載完畢回調@Overrideprotected void onPostExecute(Boolean result) {// TODO Auto-generated method stubimage.setImageBitmap(mDownloadImage);System.out.println("result = " + result);super.onPostExecute(result);}// 更新進度回調@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);}}}
假設圖片較大可能會下載失敗

Demo:http://download.csdn.net/detail/deng0zhaotai/7326167


著作權聲明:本文博主原創文章,部落格,未經同意不得轉載。

Android採用HttpClient下載圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.