[Android] Web HTML viewer

The request to visit a web page is actually a get request. There is nothing to say about the layout of the application. The linear layout defines the control, obtains the control in the activity code, obtains the network path of the EditText control, and starts the get request

Start a new thread, new thread() {}. Start()

Get the URL object and new it. Parameters: path is the URL of string. The internal class accesses the variables of the external class. It should be final once

The member property handler object is defined in the main thread. In order to directly override the handlemessage () method, the callback parameter is the message object, and the what attribute and obj attribute of the message object are obtained,

After a new URL is generated, an exception will be generated and caught,

Call the openconnection () method of the URL object to get the httpurlconnection object, which needs to be forced

Call the setrequestmethod() method of the httpurlconnection object

Call the setconnecttimeout() method of the httpurlconnection object

Call the setrequestproperty() method of the httpurlconnection object

Call the getresponsecode () method of httpurlconnection object to get the response code and judge

Call getinputstream() method of httpurlconnection object to get InputStream object

Converting stream data into text is a very common operation. Create a new package utils and put it into the tool class

Create a new class streamtools, which defines a static method readinputstream()

Get the bytearrayoutputstream object and output the stream through new a byte array

The len length of defining an int is 0

Define an array of byte [], and define an array of 1024 bytes through new byte [1024]

Define a while loop. The condition is to call the read (buffer) method of the InputStream object. Parameters: the byte [] array defined above, read the data into the byte [] array, and return a read length. If the length is equal to - 1, it is read to the end. Therefore, this loop is judged

Call the write (buffer, len) method of bytearrayoutputstream object to read the byte array from 0 to len

After the loop is completed, close the input stream, call tobytearray() of bytearrayoutputstream object to get a byte array, return it, and wrap it with new string()

Call the sendmessage() method of the handler object to send data

When setting request parameters, you can't add more colons, otherwise it's easy to make mistakes

Tools:

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
分享
二维码
< <上一篇
下一篇>>