Android Advanced: 4. Send a get network request

Android also has a network programming section. Let's start with thread communication, because Android has a feature since 4.0, that is, the main thread cannot send network requests, and sub-threads cannot update the interface, so we want to learn For network programming, you must first master the communication between threads;

1、handler:

This is the medium for communication between the main thread and the sub-threads. We used this when making carousels before. We can use it to time and send a message to the main thread regularly, and then the main thread updates the interface according to the type of information:

    /*hanlder= MyHanlder(WeakReference(this))*/
    //1.3 非静态内部类:使用WeakReference防止内存泄漏
    private class MyHanlder(var wk:WeakReference<MainActivity>):Handler(Looper.getMainLooper()){
    
    

        override fun handleMessage(msg: Message) {
    
    
            super.handleMessage(msg)
            var activity = wk.get()
           if(activity!=null){
    
    
                if(msg.what==0){
    
    
                    activity.count++
                    activity.tv_count.setText(activity.count.toString())
                }else if(msg.what==1){
    
    
                    activity.isback=false
                }
            }
        }
    }

In kotlin, we can create an internal class of our own handler in this way, because it is convenient to use the handler directly, but there is a problem that it will cause memory leaks. The handler will implicitly refer to the activity by default, and it will not be after we close the project. is destroyed, so we use a weak reference (WeakReference). As long as the object is referenced through this object, after the reference object is destroyed, that is, the mainactivity here, it will be recycled, so it will not cause memory leaks; Note In the way of writing here, we can get the implicitly referenced activity object through get(), and then update the properties inside; but we need to judge whether it is a null value

2, thread thread

Generally, we can create a child thread like this:

 Thread(){
    
    

            while(flag){
    
    
                Thread.sleep(1000)

                message.what=0
                myHanlder.sendEmptyMessage(0)
            }

        }.start()

Of course, you can also use methods that implement the Runnable interface;

3. Send get request

Android provides two ways to send requests: one is the HttpURLConnection object, the other is HttpClient (but this has been eliminated), let's learn how HttpURLConnection sends requests, as we said before, we can only send requests in Sub-thread, so we want to create a sub-thread, but we need to modify some configurations, because the default andorid studio does not allow sending requests, we need to add these two sentences in the manifest file: 2

insert image description here

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hanlderpractice">

//允许发送网络请求
    <uses-permission android:name="android.permission.INTERNET"/>
    
    <application

        //允许发送纯文本
        android:usesCleartextTraffic="true"
    
    </application>

</manifest>

After adding it, we will write our code

1. Create a URL:

 var httpurl: String = "http://10.0.2.2:5000/api/user/" + parame1
 var url: URL = URL(httpurl)
 var conn: HttpURLConnection = url.openConnection() as HttpURLConnection

We create a string, which is our URL, and then use the URL to encapsulate it into a request object, call its function openConnection and force the return value to a

HttpURLConnection object, and then we can store the requested data:

 conn.requestMethod = "GET"
conn.connectTimeout = 5000
conn.readTimeout = 5000
var code: Int = conn.responseCode
if (code == 200) {
    
    
    var inputStream: InputStream = conn.inputStream
    var byteArray: ByteArray = ByteArray(1024)
    var length: Int
    var result: String = ""

    inputStream.use {
    
    
        length = it.read(byteArray)
        result = String(byteArray)
        Log.d(TAG, "$result: ")
    }
    inputStream.close()
}

Then set the access timeout, reading timeout, and return code. We use the returned request code to determine whether it is 200. This is the code for a successful request, and then create an input stream object. We use this input stream to pass the requested Store the data in a binary array, and then print it out through the log; don't forget to close the stream at the end;

2. Create a child thread and start it in the click event


class HttpPractice : AppCompatActivity() {

    lateinit var thread: Thread
    lateinit var parame1: String

    companion object {
        private const val TAG = "HttpPractice"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_http_practice)
        //1.1 创建子线程用来发送请求
        parame1 = "[email protected]"
        thread = Thread {
            var httpurl: String = "http://10.0.2.2:5000/api/user/" + parame1
            var url: URL = URL(httpurl)
            var conn: HttpURLConnection = url.openConnection() as HttpURLConnection
            conn.requestMethod = "GET"
            conn.connectTimeout = 5000
            conn.readTimeout = 5000
            var code: Int = conn.responseCode
            if (code == 200) {
                var inputStream: InputStream = conn.inputStream
                var byteArray: ByteArray = ByteArray(1024)
                var length: Int
                var result: String = ""

                inputStream.use {
                    length = it.read(byteArray)
                    result = String(byteArray)
                    Log.d(TAG, "$result: ")
                }
                inputStream.close()
            }

        }

    }



    fun sendget(view: View) {
        //2.1 发送请求,启动线程

        thread.start()


    }
}

It is also very easy to get with parameters, we also use it here, just splice a variable in the back, and fill in the parameters we want to pass;

By the way, when you send the request, the window accesses the 127.0.0.1 port of the machine, but it is different in Android. We access the 5000 port of 10.0.2.2, and we have to start a server on the machine. , if you don’t have a local server, you can go to my official account: code stack to reply to the Android local server to get the server we use;

insert image description here
Get the file, there is something called webapi in it, and a PDF document, which is all the interfaces of the local server and the data that will be returned. We can access various interfaces by referring to this document; click here directly to
webapi.exe can be started;
insert image description here

There is also the use of postman, we can use this software to test the result of the request, that is, we can see the data returned by the visited URL:
insert image description here

Guess you like

Origin blog.csdn.net/aiwanchengxu/article/details/127628056