0%

在安卓平台建立 HTTP 连接-2

前言

本篇续上一篇,跑通了 post 请求,贴贴代码再凑一篇 Blog。Volley 在 谷歌的文档里没有看到 POST 的示例(也有可能就是我没看到)差评。

正文

POST 请求可以在 body 里放东西,因为这里我的场景是 body 里放字符串,其实也可以做类似提交表格的键值对形式。参考了下面两篇文章。

https://stackoverflow.com/questions/33573803/how-to-send-a-post-request-using-volley-with-string-body

https://stackoverflow.com/questions/22057023/android-volley-post-string-in-body

其实看到这样的文章已经会 POST 了,但是还是对 Kotlin 不熟啊,连那种继承之后重写部分方法的语法都不知道叫什么。其实就是声明了一个只用一次的匿名类,然后继承了 StringRequest 类, 然后对 getBody 等方法做了重写就可以。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
val tmpRunnable = Runnable {
run {
val textView = findViewById<TextView>(R.id.text)

// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "http://10.0.2.2:8080/test"

// Request a string response from the provided URL.
// 这里用的是一个匿名子类
val stringRequest = object:StringRequest(
Request.Method.POST, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.

if(response.toString().length < 500)
textView.text = "Response is: ${response}"
else
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener {
println(it.toString())
textView.text = "That didn't work!\n" + it.toString()
}
){
override fun getBodyContentType(): String {
return "text/plain"
}

@Throws(AuthFailureError::class)
override fun getBody(): ByteArray {
return "This is haulyn5.".toByteArray()
}

}

// Add the request to the RequestQueue.
queue.add(stringRequest)
}
}