1. First register for access to Internet services in Androidmanifest.xml:
<uses-permission android:name="android.permission.INTERNET"
(if not joined, there will be permission denied exception)
2. The code is as follows:
Package Vip.test.httpget;import java.io.bufferedinputstream;import java.io.inputstream;import Java.net.URL; Import Java.net.urlconnection;import Org.apache.http.util.bytearraybuffer;import Org.apache.http.util.encodingutils;import Vip.test.httpget.r;import Android.app.activity;import Android.os.Bundle ; Import Android.widget.TextView; Public classHttpGet extends Activity {/** Called when the activity is first created.*/@Override 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 fileURL Myurl =NewURL ("HTTP://www.baidu.com/hello.txt""); //Open URL linkURLConnection Ucon =myurl.openconnection (); //use InputStream to read data from URLConnectionInputStream is=Ucon.getinputstream (); Bufferedinputstream bis=NewBufferedinputstream ( is); //Cache with BytearraybufferBytearraybuffer BAF =NewBytearraybuffer ( -); intCurrent =0; while(current = Bis.read ())! =-1) {baf.append (byte) (current); } //Converts the cached content to a string, encoded with UTF-8myString = encodingutils.getstring (Baf.tobytearray (),"UTF-8"); } Catch(Exception e) {myString=E.getmessage (); } //Set screen displayTv.settext (myString); This. Setcontentview (TV); }}
3. Code Explanation:
1) Instance URL class: Myurl, which represents the URL to get content for:
URL myurl=new URL (HTTP://
2) An instance of the URLConnection class that represents an open network connection Ucon:
3) The data that is read from the network is expressed in the form of a byte stream:
is =ucon.getinputstream (); is =ucon.getinputstream (); Bufferedinputstream bis=new bufferedinputstream ( is
4) Read the data in the network by reading the method:
Bytearraybuffer baf=New bytearraybuffer (a); int current=0; while ((Current=bis.read ())!=-1) {baf.append ((byte
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 gets network resources via URL