我是 Kotlin 的新手。我想问一下POST请求。

我想将“nim”,“nama”和“地址” edittext.text传递给数据库。但是在我的代码上,Toast“发生错误”仍然出现,并且数据库未获取任何数据。那我该怎么办?

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val jsonobj = JSONObject()

    jsonobj.put("nim", nim_editText.text)
    jsonobj.put("nama", nama_editText.text)
    jsonobj.put("address", address_editText.text)

    val queue = Volley.newRequestQueue(this)
    val url = "http://192.168.100.7/simplecrud/create.php"

    val req = JsonObjectRequest(Request.Method.POST,url,jsonobj,
        Listener {
            Toast.makeText(this@MainActivity, "Success", Toast.LENGTH_SHORT).show()
        },
        ErrorListener {
            Toast.makeText(this@MainActivity, "Error Occured", Toast.LENGTH_SHORT).show()
        })


    val btn = findViewById<Button>(R.id.button1)

    btn.setOnClickListener(object : View.OnClickListener {
        override fun onClick(v: View?) {
            queue.add(req)
        }
    })

这是我的create.php代码
    <?php

require_once('connection.php');

$nim        = $_POST['nim'];
$name       = $_POST['name'];
$address    = $_POST['address'];
$gender     = $_POST['gender'];

if(!$nim || !$name || !$address || !$gender ){
    echo json_encode(array('message'=>'required field is empty.'));
}
    else{
        $query = mysqli_query($CON, "INSERT INTO tb_student VALUES ('$nim','$name','$address','$gender')");

    if($query){
        echo json_encode(array('message'=>'student data successfully added.'));
    }
        else{
            echo json_encode(array('message'=>'student data failed to add.'));
        }
}

?>

最佳答案

    fun post(url: String, body: String): String {
    return URL(url)
        .openConnection()
        .let {
            it as HttpURLConnection
        }.apply {
            setRequestProperty("Content-Type", "application/json; charset=utf-8")
            requestMethod = "POST"

            doOutput = true
            val outputWriter = OutputStreamWriter(outputStream)
            outputWriter.write(body)
            outputWriter.flush()
        }.let {
            if (it.responseCode == 200) it.inputStream else it.errorStream
        }.let { streamToRead ->
            BufferedReader(InputStreamReader(streamToRead)).use {
                val response = StringBuffer()

                var inputLine = it.readLine()
                while (inputLine != null) {
                    response.append(inputLine)
                    inputLine = it.readLine()
                }
                it.close()
                response.toString()
            }
        }
}

关于android - Kotlin POST请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54880874/

10-12 01:24
查看更多