这是我使用 kotlin 协程请求结果的函数。
private fun sendNotificationToUser(boardName: String, token: String): String {
var result: String
var connection: HttpURLConnection? = null
try {
val url = URL(Constants.FCM_BASE_URL)
connection = url.openConnection() as HttpURLConnection
connection.doOutput = true
connection.doInput = true
connection.instanceFollowRedirects = false
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type", "application/json")
connection.setRequestProperty("charset", "utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty(Constants.FCM_AUTHORIZATION, "${Constants.FCM_KEY}=${Constants.FCM_SERVER_KEY}")
connection.useCaches = false
val wr = DataOutputStream(connection.outputStream)
val jsonRequest = JSONObject()
val dataObject = JSONObject()
dataObject.put(Constants.FCM_KEY_TITLE, "Assigned to the Board $boardName")
dataObject.put(Constants.FCM_KEY_MESSAGE, "You have been assigned to the new board by ${mAssignedMembersList[0].name}")
jsonRequest.put(Constants.FCM_KEY_DATA, dataObject)
jsonRequest.put(Constants.FCM_KEY_TO, token)
wr.writeBytes(jsonRequest.toString())
wr.flush()
wr.close()
val httpResult: Int =
connection.responseCode
if (httpResult == HttpURLConnection.HTTP_OK) {
val inputStream = connection.inputStream
val reader = BufferedReader(InputStreamReader(inputStream))
val sb = StringBuilder()
var line: String?
try {
while (reader.readLine().also { line = it } != null) {
sb.append(line + "\n")
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
result = sb.toString()
} else {
result = connection.responseMessage
}
} catch (e: SocketTimeoutException) {
result = "Connection Timeout"
} catch (e: Exception) {
result = "Error : " + e.message
} finally {
connection?.disconnect()
}
return result
}
谁能告诉我出现此错误的可能原因是什么以及如何解决这些不同的错误。
这是我得到的最终结果 -> {“multicast_id”:4389386151184574869,“成功”:0,“失败”:1,“canonical_ids”:0,“结果”:[{“错误”:“无效注册”}]}