首页 > 解决方案 > 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 请帮助。

标签: androidjsonkotlinurl

解决方案


推荐阅读