android - URL(url).readText 返回空响应 KOTLIN ANDROID
问题描述
我有这样的代码和平:
suspend fun getWeatherResponse(locationCode: String, apiKey: String): String? {
return withContext(Dispatchers.IO) {
val apiUrl = "http://api.openweathermap.org/data/2.5/weather" +
"?q=$locationCode&appid=$apiKey"
val response: String? = try{
URL(apiUrl).readText(StandardCharsets.UTF_8)
}catch (ex: Exception){
null
}
return@withContext response
}
}
它应该返回 JSON 字符串,然后我使用响应执行此操作:
val response = getWeatherResponse(location, apiKey)
val jsonWeatherObj =
JSONObject(response ?: "{}")
但是,响应是null
。我检查了调试器,链接构建正确。如果我自己建立一个链接并在浏览器中执行它,那么我会在屏幕上得到正确的响应。
其余代码:
val main = jsonWeatherObj.getJSONObject("main")
val sys = jsonWeatherObj.getJSONObject("sys")
val wind = jsonWeatherObj.getJSONObject("wind")
val weather = jsonWeatherObj.getJSONArray("weather").getJSONObject(0)
val temp = main.getString("temp")+"°C"
val tempMin = "Min Temp: " + main.getString("temp_min")+"°C"
val tempMax = "Max Temp: " + main.getString("temp_max")+"°C"
val pressure = main.getString("pressure")
val humidity = main.getString("humidity")
val sunrise:Long = sys.getLong("sunrise")
val sunset:Long = sys.getLong("sunset")
val windSpeed = wind.getString("speed")
val weatherDescription = weather.getString("description")
val fullLocationName = jsonWeatherObj.getString("name")+", "+sys.getString("country")
val updatedAt:Long = jsonWeatherObj.getLong("dt")
val updatedAtText = "Updated at ${SimpleDateFormat(
"dd/MM/yyyy hh:mm a", Locale.ENGLISH).format(Date(updatedAt*1000))}"
val sunriseText = SimpleDateFormat(
"hh:mm a", Locale.ENGLISH).format(Date(sunrise*1000))
val sunsetText = SimpleDateFormat(
"hh:mm a", Locale.ENGLISH).format(Date(sunset*1000))
weatherObject.value = WeatherInfo(fullLocationName, temp, tempMin, tempMax, updatedAtText, weatherDescription,
"", pressure, humidity, windSpeed, sunriseText, sunsetText)
}
我得到了这个例外:org.json.JSONException: No value for main
请帮助。
解决方案
推荐阅读
- r - 使用 R 进行特征提取
- sql - 对依赖于另一列值 SQL 的列进行条件排序
- java - 如何使用文档 ID Cloud Firestore 为查询创建索引
- javascript - 使用 ajax/php 将 JSON 对象解析为 javascript
- javascript - 使用 React Rudux 更改输入值
- r - 使用 geom = "errorbars" 的错误栏位置错误
- python - 函数子段的 Python 装饰器
- html - 设置 CSS 网格中第一行的高度
- c - 从文件输入(使用命令行),然后是普通的标准输入键盘输入(C)
- mysql - mysql LEFT JOIN 主表和两个附加表,每个表都有最大值