代码:
private suspend fun sendJsonFile(file: File) {
val url = URL(EC2_URL)
val urlConnection = url.openConnection() as HttpURLConnection
try {
sendJsonFileLog = "Preparing to send file: ${file.name}"
// Set timeouts for connection and read operations
urlConnection.connectTimeout = 50000
urlConnection.readTimeout = 100000
urlConnection.requestMethod = "POST"
urlConnection.setRequestProperty("Content-Type", "application/json")
urlConnection.setRequestProperty("Content-Encoding", "gzip")
urlConnection.doOutput = true
// Read file and compress JSON data
val jsonInputString = file.readText()
val byteArrayOutputStream = ByteArrayOutputStream()
GZIPOutputStream(byteArrayOutputStream).use { gzipOutputStream ->
gzipOutputStream.write(jsonInputString.toByteArray())
}
val compressedData = byteArrayOutputStream.toByteArray()
sendJsonFileLog = "JSON data compressed"
// Send compressed JSON data
urlConnection.outputStream.use { os ->
os.write(compressedData)
os.flush()
}
sendJsonFileLog = "Compressed data sent"
// Handle HTTP response codes
val responseCode = urlConnection.responseCode
sendJsonFileLog += " - Response code: $responseCode"
if (responseCode == HttpURLConnection.HTTP_OK) {
file.delete()
sendJsonFileLog += " - File deleted."
updateList()
} else {
handleHttpError(responseCode, urlConnection.responseMessage)
}
} catch (e: IOException) {
sendJsonFileLog = "Network error: ${e.localizedMessage}"
handleNetworkError(e)
} catch (e: Exception) {
sendJsonFileLog = "Unexpected error: ${e.localizedMessage}"
handleUnexpectedError(e)
} finally {
urlConnection.disconnect()
sendJsonFileLog += " - Connection closed."
}
}
`
上面的 android studio Kotlin 代码可以完美地将 JSON 对象发送到 EC2 实例存储的应用程序。但是,对于仅某些设备上的蜂窝数据,它根本不会发送。没有错误代码,只有重新连接 WiFi 时超时。有什么想法吗?
用户已尝试通过wifi使用该应用程序并取得成功。 大多数用户通过蜂窝网络成功使用该应用程序,但也有一些用户没有。通过蜂窝网络遇到此问题的用户每次都创建了类似的 JSON 对象,但通过蜂窝网络没有成功。
首先听起来像是路由/连接。不是应用程序问题。
EC2_URL
是否有防火墙? (因此只能从某些地方访问)GET
上的 EC2_URL
有 some响应,您可以用它来证明您可以从客户端路由到服务器?如果是这样,那么让用户在设备上的网络浏览器中使用它......(这将证明/反驳您的代码与它有任何关系)