Android uses URL to read network resources

URL (uniform resource locator) is a unified resource locator. It is a concise representation of the location and access method of resources available from the Internet. It is the address of standard resources on the Internet. Every file on the Internet has a unique URL, which contains information indicating the location of the file and what the browser should do with it. In general, URLs can consist of protocol names, hosts, ports, and resources.

The URL class provides multiple constructors for creating URL objects. Once the URL object is obtained, you can call the following common methods to access the resources corresponding to the URL. - > String getfile(): get the resource name of this URL; - > String gethost(): get the host name of this URL; - > String getpath(): get the path part of this URL; - > String getport(): get the port number of this URL; - > String getprotocol(): get the protocol name of this URL; - > String getquery(): get the query string part of this URL; - > Urlconnection openconnection(): returns a urlconnection object that represents the connection to the remote object referenced by the URL; InputStream openstream(): open the connection to this URL and return an InputStream used to read the URL resource.

The first several methods in the URL object are very easy to understand, and the openstream () provided by the object can read the InputStream of the URL resource. Through this method, it is very convenient to read the remote resource.

The following program demo demonstrates how to read remote resources through the URL class.

layout/activity_ The main.xml interface layout code is as follows:

The logic code of mainactivity.java is as follows:

The above program demo calls the openstream () method of the URL object twice to open the input stream of the resource corresponding to the URL. For the first time, the program uses the decodestream (InputStream) method of bitmapfactory to parse the pictures in the input stream; The second time, use IO to download the pictures in the input stream to the local. Note: since the program needs to access the Internet, it also needs to authorize the permission to access the Internet in the manifest file androidmanifest.xml:

The screenshot of demo program running effect interface is as follows:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>