POST request
class MainActivity : AppCompatActivity() {
private var accEdt: EditText? = null
private var pwdEdt: EditText? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
accEdt = findViewById(R.id.account)
pwdEdt = findViewById(R.id.pwd)
}
fun myclick(view: View) {
when (view.id) {
R.id.get -> object : Thread() {
override fun run() {
super.run()
get()
}
}.start()
R.id.post -> {
val account = accEdt!!.text.toString()
val pwd = pwdEdt!!.text.toString()
object : Thread() {
override fun run() {
super.run()
post(account, pwd)
}
}.start()
}
}
}
fun post(account: String, pwd: String) {
try {
val url = URL("http://www.imooc.com/api/okhttp/postmethod")
val conn = url.openConnection() as HttpURLConnection
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 6000
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
val out = conn.outputStream
out.write("account=$account&pwd=$pwd".toByteArray())
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
val inputStream = conn.inputStream
val b = ByteArray(1024)
var len = 0
val baos = ByteArrayOutputStream()
while (inputStream.read(b).also {
len = it } > -1) {
baos.write(b, 0, len)
}
val s = String(baos.toByteArray())
Log.e("TAG", "$s====")
}
} catch (e: IOException) {
e.printStackTrace()
}
}
GET & POST comparison
GET
- Requests can be cached, kept in browser history, and bookmarked
- Not suitable for processing sensitive data
- There are restrictions on the data length
- Used to obtain data
POST
- Requests cannot be cached, cannot be kept in browser history, cannot be bookmarked
- safer
- No limitation on data length
- Used to submit data