As a mobile platform application, must avoid the exchange of data with the network, whether it is to read the Web page data, or call API interface, have to master the HTTP communication technology
Using get to communicate with the network is the most common HTTP communication, and after the link is established, the network data can be read through the input stream.
Code:
Public class mainactivity extends Activity { @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Button btn= (button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View view) {//Asynchronous Load NewAsynctask<string,void,void> () {@Override protectedVoidDoinbackground(String ... strings) {Try{URL url=NewURL (strings[0]); URLConnection connection=url.openconnection ();//Get an Internet connectionInputStream Is=connection.getinputstream ();//Get input streamInputStreamReader isr=NewInputStreamReader (IS,"Utf-8");//Byte to character, character set is Utf-8BufferedReader bufferedreader=NewBufferedReader (ISR);//Through BufferedReader can read a line of stringString Line; while((Line=bufferedreader.readline ())! =NULL) {LOG.I ("Output:",""+line); } bufferedreader.close (); Isr.close (); Is.close (); }Catch(Malformedurlexception e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); }return NULL; }//Data interface using the API}.execute ("http://fanyi.youdao.com/openapi.do?keyfrom=testdemoHttpGet&key=660196743&type=data&doctype= Xml&version=1.1&q=good "); } }); }}
Layout
<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns:tools =" Http://schemas.android.com/tools " android:layout_width = "match_parent" android:orientation =" vertical " android:layout_height = "match_parent" tools:context = " Custom.community.com.filedemo.MainActivity "; <buttonandroid:id="@+id/btn"android:text="read data"Android : Layout_width="Wrap_content"android:layout_height="wrap_content" /> </linearlayout>
Androidmanifest.xml Configuring the Network
<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android" package ="Custom.community.com.filedemo"> <applicationandroid:allowbackup="true"android:icon="@mipmap/ Ic_launcher "android:label=" @string/app_name "android:supportsrtl=" True "android:theme=" @style/apptheme "> <activity android:name=". Mainactivity "> <intent-filter> <action android:name="Android.intent.action.MAIN" /> <category android:name="Android.intent.category.LAUNCHER" /> </intent-filter> </activity> </Application>**<uses-permission android:name="Android.permission.INTERNET"/>**</manifest>
Android reads network data using the Get mode of HTTP