Network Programming series in Android (1): URLConnection

Source: Internet
Author: User

Network Programming series in Android (1): URLConnection

 

The URL (Uniform Resource Locator) object represents a unified Resource Locator, which is a pointer to Internet resources. The URL consists of the protocol name, host, port, and resource Path Components:

 

protocol://host:port/path

 

 

For example, http://kan.sogou.com/dianying/#a urladdress.

URL provides multiple constructor methods for creating URL objects. The main methods provided by URL are as follows:

 

(1) String getFile (): gets the Resource Name of this URL;

(2) String getHost (): Get the host name of this URL;

(3) String getPath (): obtains the path of the URL;

(4) String getProtocol (): Get the protocol name of this URL;

(5) String getQuery (): Obtain the query String of this URL;

(6) URLConnection openConnection (): returns a URLConnection object, which indicates the connection between the remote object referenced by the URL and the local process;

(7) InputStream openStream (): Open the connection to this URL and return an InputStream used to read the URL resource;

The following uses the example of downloading an image of death on Baidu to demonstrate how to use a URL:

The layout file is very simple. Two buttons and one ImageView are not attached. The following is the source code:

 

Public class MainActivity extends Activity implements View. onClickListener {private static final String PIC_URL = http://pic7.nipic.com/20100528/4981527_163140644317_2.jpg;private static final int SHOW_IMAGE = 0x123; private static final int SAVE_SUCC = 0x124; private static final int SAVE_ERROR = 0x125; button showImageButton, saveImageButton; ImageView imageView; Bitmap bitmap; private Handler handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {if (msg. what = SHOW_IMAGE) {imageView. setImageBitmap (bitmap);} else if (msg. what = SAVE_SUCC) {Toast. makeText (getBaseContext (), the image is saved successfully, Toast. LENGTH_LONG ). show ();} else if (msg. what = SAVE_ERROR) {Toast. makeText (getBaseContext (), image saving error, Toast. LENGTH_LONG ). show () ;}}; private void initView () {showImageButton = (Button) findViewById (R. id. showImageButton); saveImageButton = (Button) findViewById (R. id. saveImageButton); imageView = (ImageView) findViewById (R. id. imageView) ;}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initView (); showImageButton. setOnClickListener (this); saveImageButton. setOnClickListener (this) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;} private void showImage () {new Thread () {@ Overridepublic void run () {try {URL url = new URL (PIC_URL ); inputStream is = url. openStream (); bitmap = BitmapFactory. decodeStream (is); handler. sendEmptyMessage (SHOW_IMAGE); is. close ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}. start ();} public void saveImage () {new Thread () {@ Overridepublic void run () {try {URL url = new URL (PIC_URL); InputStream is = url. openStream (); BufferedInputStream bis = new BufferedInputStream (is); String filepath+animation.png; FileOutputStream fos = getBaseContext (). openFileOutput (filePath, MODE_PRIVATE); BufferedOutputStream bos = new BufferedOutputStream (fos); byte [] buff = new byte [32]; int hasRead = 0; while (hasRead = bis. read (buff)> 0) {bos. write (buff, 0, hasRead);} bos. close (); fos. close (); bis. close (); is. close (); handler. sendEmptyMessage (SAVE_SUCC);} catch (Exception ex) {handler. sendEmptyMessage (SAVE_ERROR); ex. printStackTrace ();}}}. start () ;}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. showImageButton: showImage (); break; case R. id. saveImageButton: saveImage (); break ;}}}

Data/com. android. in urlsample/files, note that the order of closing the stream is the opposite to that of creating the stream. Otherwise, an exception is thrown.

 

 

 

 

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.