Android uses HttpClient to download images

Source: Internet
Author: User

In the previous chapter, Android uses HttpURLConnection to download images. In this chapter, HttpClient is used to download images.

Differences between HttpURLConnection and HttpClient:

HttpClient is a good open-source framework (org. appache. http) that encapsulates the request headers, parameters, content bodies, and responses for accessing http. It is more powerful to use.
HttpURLConnection is a standard java class that can implement simple URL-based request and response functions without encapsulation. It can be used in Taiyuan, such as custom re-access and some advanced functions.

Add HttpClient based on the previous chapter


Key download code <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PHByZSBjbGFzcz0 = "brush: java;">/*** Get webpage content through Get ** @ param url * For example: 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; // create a default connection HttpClient client = new DefaultHttpClient (); // create a Get method HttpGet Get = new HttpGet (url); // get the network response HttpResponse response = client.exe cute (get); // if the server returns OK! If (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {InputStream is = response. getEntity (). getContent (); bitmap = BitmapFactory. decodeStream (is); is. close () ;}return bitmap ;}

Internet access permission

 

Activity download code

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. dz T. 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 downloa DImageTask () ;}@ Overrideprotected void onStop () {// TODO Auto-generated method stubsuper. onStop (); if (_ isExe) {task. cancel (true); // cancel Operation} 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. downl Oad_btn: if (! _ IsExe) cmdtask.exe cute ("http://preview.quanjing.com/is002/ev601-025.jpg"); // execute asynchronous operations _ isExe = true;} break; default: break;} class downloadImageTask extends AsyncTask
 
  
{@ 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;} // callback for download completion @ Overrideprotected void onPostExecute (Boolean result) {// TODO Auto-generated method stubimage. setImageBitmap (mDownloadImage); System. out. println ("result =" + result); super. onPostExecute (result);} // Update Progress callback @ Overrideprotected void onProgressUpdate (Integer... values) {// TODO Auto-generated method stubsuper. onProgressUpdate (values );}}}
 
If the image size is large, the download may fail.

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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.