Android uses httpclient to download images

Source: Internet
Author: User

In the previous chapter, I talked about Android using httpurlconnection to download images, this chapter uses httpclient to download pictures

The difference between HttpURLConnection and httpclient:

HttpClient is a very good open source framework (ORG.APPACHE.HTTP) that encapsulates the request header, the number of references, and the content body of an access HTTP. Response, and so on, more powerful to use.
HttpURLConnection is a standard Java class that enables simple URL-based requests, response functions, and nothing encapsulation. It's too primitive to use. For example, re-visit your own definition, as well as some advanced features.

Or add httpclient on the basis of the previous chapter


Key download code

/** * get Web content via get *  * @param URL *            such as: Http://preview.quanjing.com/is002/ev601-025.jpg * @return * @throws CLIENTPR Otocolexception * @throws IOException * @date 2014.05.10 */public static Bitmap gethttpgetbitmap (String url) throws CLIENTP Rotocolexception, IOException {Bitmap Bitmap = null;//Create a new default connection HttpClient client = new Defaulthttpclient ();//Create a new Get method h Ttpget get = new HttpGet (URL),//Get the response of the network HttpResponse response = Client.execute (get);//Suppose the server responds with OK!

if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {InputStream is = response.getentity (). GetContent () ; bitmap = Bitmapfactory.decodestream (is); Is.close ();} return bitmap;}

Internet access

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

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.dzt.downloadimage.utils.httputils;public Class Mainactivity extends Activity implements Onclicklistener {private Bitmap mdownloadimage = null;private ImageView ima GE = null;private Downloadimagetask task;private Boolean _isexe = false; @Overrideprotected void OnCreate (Bundle savedinst Ancestate) {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);//Cancel operator Make}}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 (!_i SExe) {Task.execute ("http://preview.quanjing.com/is002/ev601-025.jpg");//Run asynchronous operation _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) {/////T ODO 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;} Download complete callback @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);}}}
Assuming a larger picture may fail to download

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


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Android uses httpclient to download images

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.