我正在运行基于 Yahoo Weather API 的基本获取请求。这是来自 Youtube 的示例。我无法让它运行。我在 doInBackground 方法中的 HTTP 请求中遇到运行时错误。 (见下文)。
我在手机上收到错误消息“Java.lang.boolean 类型的值 True 无法转换为 JSON 对象”。所以我需要返回一个字符串。但是当我将“行”的类型更改为字符串时,它会给出错误“不兼容的类型 - 需要 java.lang.String - 找到 boolean 值”。所以 BufferedReader 的 readline 命令需要一个字符串,但找到一个 boolean 值。任何人都可以向我解释发生了什么以及如何解决这个问题吗?
提前致谢!
public void refreshWeather(最终字符串位置){
new AsyncTask<String, Void, String>()
{
@Override
protected String doInBackground(String... strings) {
String YQL = String.format("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"%s\")",location);
String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));
try {
URL url = new URL(endpoint);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
boolean line;
while ((line = reader.readLine()!= null)){
result.append(line);
}
return result.toString();
} catch (Exception e) {
error = e;
}
return null;
}
/**
onPostExecute checks first if there is a service failure, then if city is valid, then it
populates the data from the city and goes to method serviceSuccess and populates the fields with the retrieved data
*/
@Override
protected void onPostExecute(String s) {
if (s == null && error != null){
callback.serviceFailure(error);
return;
}
try {
JSONObject data = new JSONObject(s);
JSONObject queryResults = data.optJSONObject("query");
int count = queryResults.optInt("count");
if (count == 0){
callback.serviceFailure(new LocationWeatherException("No Weather Info Found for" + location));
return;
}
Channel channel = new Channel();
channel.populate(queryResults.optJSONObject("results").optJSONObject("channel"));
callback.serviceSuccess(channel);
} catch (JSONException e) {
callback.serviceFailure(e);
}
}
}.execute(location);
}
最佳答案
当您在 java 中进行比较时,您使用 ==
检查。在进行比较时也不要设置变量,例如:line = reader.readLine()!= null
这将导致错误,因为您在检查它是否等于什么时尝试设置变量名。
尝试在调用之前设置变量,然后使用 line != null
例如:
line = reader.readLine();
if(line != null) {
//do something
}
关于java - HTTP Get 请求 - 不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47800234/