Android network_network source code viewer, android source code
Xml design
<? Xml version = "1.0"?> -<LinearLayout tools: context = ". mainActivity "android: paddingTop =" @ dimen/activity_vertical_margin "android: paddingRight =" @ dimen/activity_horizontal_margin "android: paddingLeft =" @ dimen/plugin "android: paddingBottom = "@ dimen/Docs" android: orientation = "vertical" android: layout_height = "match_parent" android: layout_width = "match_parent" xmlns: tools = "http://schemas.android.com/tools" xmlns: android = "http://schemas.android.com/apk/res/android"> <EditText android: id = "@ + id/et_url" android: layout_height = "wrap_content" android: layout_width = "fill_parent" android: text = "http://www.baidu.com"/> <Button android: id = "@ + id/bt_looksource" android: layout_height = "wrap_content" android: layout_width = "fill_parent" android: text = "view source code"/>-<ScrollView android: layout_height = "wrap_content" android: layout_width = "wrap_content"> <TextView android: id = "@ + id/TV _source" android: layout_height = "match_parent" android: layout_width = "match_parent"/> </ScrollView> </LinearLayout>Controls
Java
Package com. itheima. sourcelook; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import java.net. URLConnection; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. app. activity; import android. content. context; import android. text. textUtils; import android. view. menu; import android. view. view; import android. vie W. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity implements OnClickListener {private EditText et_url; private TextView TV _source; private Context mContext; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setConten TView (R. layout. activity_main); mContext = this; et_url = (EditText) findViewById (R. id. et_url); Button bt_looksource = (Button) findViewById (R. id. bt_looksource); TV _source = (TextView) findViewById (R. id. TV _source); // 2. set the Click Event bt_looksource.setOnClickListener (this); System. out. println ("oncreate method Thread:" + Thread. currentThread (). getName ();} // ☆☆☆1. create a Handler object private Handler handler Handler = new Handler () {// ☆☆☆2. override the handlermessage method of handler to receive the public void handleMessage (android. OS. message msg) {// ☆☆☆5. receives data sent by the subthread and processes the data. String result = (String) msg. obj; // ☆☆☆6. the current method belongs to the main thread which can be used to update the UI // 5. obtain the content returned by the server and display it to TV _source.setText (result) ;};}; @ Override public void onClick (View v) {try {// 3. in the oclick method, obtain the url entered by the user. final String url_str = et_url.getText (). toString (). trim (); if (TextUtils. isEmpty (url_str) {Toast. makeText (mContext, "url cannot be blank", 0 ). show (); return;} System. out. println ("oclick method Thread:" + Thread. currentThread (). getN Ame (); // create a subthread for network requests new Thread (new Runnable () {@ Override public void run () {try {System. out. println ("oclick method runnable Thread:" + Thread. currentThread (). getName (); // 4. request url // 1. create a Url object URL = new url (url_str); // 2. obtain the url of the UrlConnection object HttpURLConnection connection = (HttpURLConnection. openConnection (); // 3. set Request Parameters, request methods, and connection timeout for the UrlConnection object. setRequestMethod ("GET"); // sets the Request Method c. Onnection. setConnectTimeout (1000*10); // set the timeout time // 4. before obtaining the data of a url request, you need to determine the response code: 200: Successful, 206: access part of the data is successful. 300: jump or redirect: 400: Error 500: Server exception int code = connection. getResponseCode (); if (code = 200) {// 5. obtain valid data and parse the obtained stream data to String InputStream inputStream = connection. getInputStream (); String result = StreamUtils. streamToString (inputStream); // ☆☆☆3. create a Message object in the Child thread to carry the data obtained in the Child thread to the main thread. Message msg = new Message (); msg. obj = result; // encapsulate the obtained data in msg. // ☆☆☆4. Use the handler object to send the message to the main thread. Handler. sendMessage (msg) ;}} catch (Exception e) {e. printStackTrace ();}}}). start ();} catch (Exception e) {e. printStackTrace ();}}}MainActivity
Package com. itheima. sourcelook; import java. io. byteArrayOutputStream; import java. io. inputStream; public class StreamUtils {public static String streamToString (InputStream in) {String result = ""; try {// create a byte array to write the stream ByteArrayOutputStream out = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int length = 0; while (length = in. read (buffer ))! =-1) {out. write (buffer, 0, length); out. flush ();} result = out. toString (); // convert byte streams to string out. close ();} catch (Exception e) {e. printStackTrace ();} return result ;}}StreamUtils -- package -- byte -- string
Instructor notes
#01 Web html source code Viewer
Internet permissions are required to access the network:
Android. permission. INTERNET
Use UrlConnection to request a url to obtain the content:
// 1. Create a Url object
URL url = new URL (url_str );
// 2. Get a UrlConnection object
HttpURLConnection connection = (HttpURLConnection) url. openConnection ();
// 3. Set Request Parameters, request methods, and connection timeout for the UrlConnection object
Connection. setRequestMethod ("GET"); // sets the request method.
Connection. setConnectTimeout (1000*10); // set the timeout value.
// 4. determine the response code before obtaining the data of the url request, 200: Success, 206: access part of the data successful 300: jump or redirect 400: Error 500: Server exception
Int code = connection. getResponseCode ();
If (code = 200 ){
// 5. Get valid data and parse the obtained stream data into a String
InputStream inputStream = connection. getInputStream ();
String result = StreamUtils. streamToString (inputStream );
Note:
1. ANR: application not response the application has no response; time-consuming operations (requesting network, copying large files, and database operations) in androoid need to be done in the Child thread.
09-02 01:52:40. 711: E/ActivityManager (857): ANR in com. itheima. sourcelook (com. itheima. sourcelook/. MainActivity)
2. After 4.0, network operations must be performed in sub-threads. Because network access is time-consuming, it may cause ANR
09-02 01:57:32. 879: W/System. err (1789): android. OS. NetworkOnMainThreadException
3. The error thread calls an exception. The subthread cannot update the UI (control content)
09-02 02:02:08. 873: W/System. err (1858): android. view. ViewRootImpl $ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
The main thread cannot perform time-consuming operations. network requests are time-consuming operations that need to be placed in subthreads. The sub-thread cannot update the control content (update the Ui ). So there is a conflict. The solution is to use Handler.