android - 将 Curl Post 与请求队列 Kotlin Android 相结合
问题描述
以下适用于 REST api,但是我现在正试图在 Android Kotlin 中实现相同的效果
curl -X POST \
-H 'content-type:application/json' \
-d '{"userid":"testid","first_name":"test_first_name"}' \
http://localhost:5000/users
我尝试在 kotlin 中调用相同的 curl:
fun submit_new_user(view: View) {
val textView = findViewById<TextView>(R.id.textView111)
// ...
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
//build the curl
val requestBody = "userid=testid" + "&first_name=test_first_name"
// Request a string response from the provided URL.
val url = "http://localhost:5000/users?" + requestBody
val stringRequest = StringRequest(
Request.Method.POST, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
textView.text = "Response is: ${response.substring(0, 20)}"
},
Response.ErrorListener { textView.text = "That didn't work!" } )
// Add the request to the RequestQueue.
queue.add(stringRequest)
}
任何人都可以解释一些安全问题
解决方案
通过使用另一个问题的这个解决方案让它工作,
https://stackoverflow.com/a/40118803/2203917
val textView = findViewById<TextView>(R.id.textView111)
val url = "http://localhost:5000/users"
val sr: StringRequest = object : StringRequest(
Method.POST, url,
Response.Listener { response -> textView.text = "Response is: ${response.substring(0, 20)}" },
Response.ErrorListener { error -> textView.text = "That didn't work!" }) {
@Throws(AuthFailureError::class)
override fun getBody(): ByteArray {
val params2 = HashMap<String?, String?>()
params2["userid"] = "testid"
params2["email_address"] = "testemail@example.com"
return JSONObject(params2 as Map<*, *>).toString().toByteArray()
}
override fun getBodyContentType(): String {
return "application/json"
}
}
// Add the request to the RequestQueue.
Volley.newRequestQueue(this).add(sr)
如果有任何安全问题可以改进,请发表评论。