对于那些使用 $_POST 在 php 页面上接收请求时遇到问题的人,因为您期望键值对:
虽然所有答案都非常有帮助,但我对实际发布哪个字符串缺乏一些基本的了解,因为在我使用的旧 apache HttpClient 中
new UrlEncodedFormEntity(nameValuePairs); (Java)
然后可以在 php 中使用 $_POST 来获取键值对。
据我了解,现在有人在发布之前手动构建了该字符串。所以字符串需要看起来像
val data = "key1=val1&key2=val2"
但只是将其添加到它发布的 url(在标题中)。
另一种方法是使用 json-string 代替:
val data = "{\"key1\":\"val1\",\"key2\":\"val2\"}" // {"key1":"val1","key2":"val2"}
并在没有 $_POST 的情况下将其拉入 php:
$json_params = file_get_contents('php://input');
// echo_p("Data: $json_params");
$data = json_decode($json_params, true);
在这里您可以找到 Kotlin 中的示例代码:
class TaskDownloadTest : AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void): Void? {
var urlConnection: HttpURLConnection? = null
try {
val postData = JsonObject()
postData.addProperty("key1", "val1")
postData.addProperty("key2", "val2")
// reformat json to key1=value1&key2=value2
// keeping json because I may change the php part to interpret json requests, could be a HashMap instead
val keys = postData.keySet()
var request = ""
keys.forEach { key ->
// Log.i("data", key)
request += "$key=${postData.get(key)}&"
}
request = request.replace("\"", "").removeSuffix("&")
val requestLength = request.toByteArray().size
// Warning in Android 9 you need to add a line in the application part of the manifest: android:usesCleartextTraffic="true"
// https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted
val url = URL("http://10.0.2.2/getdata.php")
urlConnection = url.openConnection() as HttpURLConnection
// urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") // apparently default
// Not sure what these are for, I do not use them
// urlConnection.setRequestProperty("Content-Type", "application/json")
// urlConnection.setRequestProperty("Key","Value")
urlConnection.readTimeout = 5000
urlConnection.connectTimeout = 5000
urlConnection.requestMethod = "POST"
urlConnection.doOutput = true
// urlConnection.doInput = true
urlConnection.useCaches = false
urlConnection.setFixedLengthStreamingMode(requestLength)
// urlConnection.setChunkedStreamingMode(0) // if you do not want to handle request length which is fine for small requests
val out = urlConnection.outputStream
val writer = BufferedWriter(
OutputStreamWriter(
out, "UTF-8"
)
)
writer.write(request)
// writer.write("{\"key1\":\"val1\",\"key2\":\"val2\"}") // {"key1":"val1","key2":"val2"} JsonFormat or just postData.toString() for $json_params=file_get_contents('php://input'); json_decode($json_params, true); in php
// writer.write("key1=val1&key2=val2") // key=value format for $_POST in php
writer.flush()
writer.close()
out.close()
val code = urlConnection.responseCode
if (code != 200) {
throw IOException("Invalid response from server: $code")
}
val rd = BufferedReader(
InputStreamReader(
urlConnection.inputStream
)
)
var line = rd.readLine()
while (line != null) {
Log.i("data", line)
line = rd.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
urlConnection?.disconnect()
}
return null
}
}