1, first registered in the Androidmanifest.xml to access the Internet service permissions:
<uses-permission android:name= "Android.permission.INTERNET"/>
(if not joined, there will be permission denied exception)
2.
1 PackageVip.test.HttpGet;2 ImportJava.io.BufferedInputStream;3 ImportJava.io.InputStream;4 ImportJava.net.URL;5 Importjava.net.URLConnection;6 ImportOrg.apache.http.util.ByteArrayBuffer;7 Importorg.apache.http.util.EncodingUtils;8 ImportVIP.TEST.HTTPGET.R;9 Importandroid.app.Activity;Ten ImportAndroid.os.Bundle; One ImportAndroid.widget.TextView; A Public classHttpGetextendsActivity { - /**Called when the activity is first created.*/ - @Override the Public voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.main); -TextView TV =NewTextView ( This); +String myString =NULL; - Try { + //defines the URL that gets the contents of the file AURL Myurl =NewURL ( at"HTTP://www.baidu.com/hello.txt""); - //Open URL link -URLConnection Ucon =myurl.openconnection (); - //use InputStream to read data from URLConnection -InputStream is =Ucon.getinputstream (); -Bufferedinputstream bis =NewBufferedinputstream (IS); in //Cache with Bytearraybuffer -Bytearraybuffer BAF =NewBytearraybuffer (50); to intCurrent = 0; + while(current = Bis.read ())! =-1) { -Baf.append ((byte) (current); the } * //Converts the cached content to a string, encoded with UTF-8 $myString = encodingutils.getstring (Baf.tobytearray (), "UTF-8");Panax Notoginseng}Catch(Exception e) { -MyString =e.getmessage (); the } + //Set screen display A Tv.settext (myString); the This. Setcontentview (TV); + } -}
3. Code Explanation:
1) Instance URL class: Myurl, which represents the URL to get content for:
URL myurl=new url (HTTP://www.baidu.com/hello.txt);
2) An instance of the URLConnection class that represents an open network connection Ucon:
URLConnection ucon=myurl.openconnection ();
3) The data that is read from the network is expressed in the form of a byte stream:
InputStream Is=ucon.getinputstream ();
To avoid frequent reading of byte stream, improve reading efficiency, read byte stream with Bufferedinputstream cache
InputStream Is=ucon.getinputstream ();
Bufferedinputstream bis=new Bufferedinputstream (IS);
4) Read the data in the network by reading the method:
Bytearraybuffer baf=new Bytearraybuffer (50);
int current=0;
while ((Current=bis.read ())!=-1)
{
Baf.append ((byte) current);
}
5) Since the read data is only a byte stream and cannot be displayed directly on the screen, the byte stream must be converted to a readable string before the display:
Mystring=encodingutils.getstring (Baf.tobytearray ()," utf-8");
(If you read a. txt file that is in UTF-8 format, you need to convert the data specifically)
android-access to network resources via URLs