Android foundation - Network Technology

1, Request network using HttpURLConnection

HttpURLConnection use

First, you need to get the instance of HttpURLConnection. Generally, you only need to create a URL object, pass in the network address of the target, and then call the following openConnection() method.
As follows:

val url = URL(" "); / / pass in a target address to create a URL object
val connection = url.openConnection() as HttpURLConnection     // Use the openConnection method in the URL object to establish a connection

After obtaining the instance, you can set the methods required by the following HTTP requests. There are two common methods: GET and POST, which represent obtaining and submitting data respectively. Set the request to GET as follows:

connection.requestMethod = "GET"

Then call getInputStream() method to get the input stream returned by the server. The remaining task is to read the input stream:

val input = connection.inputStream

Finally, you can call the disconnect() method to close the HTTP connection:


Code example

The request string is used to encapsulate the request string of lconnection:

//Define a class HttpGetResult to obtain the target address data, which is used to request json string from the server, define the main method and data, initialize the data, and declare that it is a data class.
data class HttpGetResult(private val url: String, val token: String = "", var result: String? = "") {
    init{ // Principal construction function
        val thread01 = Thread{ // In Android 4 If the main thread uses the request network after 0, an error will be reported, so a sub thread needs to be started here
            var connection: HttpURLConnection? = null; // Defining an HttpURLConnection object requires declaring that it is mutable and initializing to null
            try {
                val url = URL(this.url)//Use the address string passed in by the main construction method to create an object of the unified resource locator
                connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                reader.forEachLine {
                        result += it
            } catch (e: Exception) {     // Catch exception
                Log.d("msg", e.toString())
            } finally {
                connection?.disconnect() // Manually release the connection
        thread01.start() // Remember to start the thread after creating the thread
        thread01.join(10000) // The main thread waits for the end of the sub thread for up to ten seconds
        result = result.replace("null","\"0\"") // Replace the obtained json string content
        result = result.replace("\\{\\}","\"0\"")

2, Request network using OkHttp

OkHttp introduction

   of course, the android request network can not only use HttpURLConnection. There are many excellent network communication libraries that can replace the native HttpURLConnection, such as OkHttp.
  OkHttp is made by Square Developed by the company, OkHttp is not only simple and easy to use in interface packaging. Even the underlying implementation is a school of its own. Compared with the original HttpURLConnection, it can be said to be better than it. Now it has become the preferred network communication library for android developers.
  OkHttp's project address is: Web page connection.
  before using OkHttp, you need to add the dependency of OkHttp Library in the project. Then app / build Add the following contents to dependencies under gradle file:

    implementation 'com.squareup.okhttp3:okhttp:4.1.0'

Use of OkHttp

To use OkHttp, you first need to create an OkHttpClient requester object.

val client = OkHttpClient()

If you want to initiate an Http Request, you need to create a Request object:

val request = Request.Builder().build()

Of course, the above code just creates an empty object and has no practical effect. We can enrich the Request object by concatenating many other methods before the build() method. For example, you can set the network address of the target through the url() method, as shown below.

val request = Request.Builder()

Then Call the newCall() method of OkHttpClient to create a Call object, and Call its execute() method to send the request and obtain the data returned by the server, as shown below:

val response = client.newCall(request).execute()

The resonse object is the data returned by the server. We can use the following method to get the specific content of the return:

val responseData = reponse.body?.string()

If a POST request is initiated, it will be slightly more complex than a GET request. We need to build a Request Body object to store the parameters to be submitted, as shown below:

val requestBody = FormBody.Builder()

Then in request The following post() method is called in the builder and the RequestBody object is passed in:

val request = new Request.Builder()

Code example

The following is a tool class for requesting data encapsulated with OkHttp, which is used to request json strings:

data class HttpGetResult(private val url: String, val token: String = "", var result: String? = "") {
    //The following main constructor uses okHttp to obtain strings, and dependencies need to be added
        val thread01 = Thread{
                /*First, create an OKHttpClient object*/
                val client = OkHttpClient()
                val request = Request.Builder().url(this.url).build() // Create request object
                val response = client.newCall(request).execute() // Use newCall to receive the request object, execute() to send the request and return a response response object
                val responseData = response.body?.string() // Converts the body content of the received response object into a string
                //Judge whether the response is empty. If it is empty, perform the operation of splicing strings. Here, the functional api is used
                responseData?.let {
                    result += it
                The above statement is equivalent to
                    result += responseData
                result = null
        //Open child thread
        //Wait for the child thread to end
        result = result?.replace("null","\"0\"")
        result = result?.replace("\\{\\}","\"0\"")


Tags: Android kotlin

Posted by NikkiLoveGod on Sun, 15 May 2022 14:55:05 +0300