我试图做一个简单的天气应用程序,允许用户输入他们的城市,它将返回天气数据。我使用了一个带有EditText的片段,并且我使用接口将字符串传递给MainActivity,这需要在URL字符串中连接,这就是问题所在。获取异常错误,我相信没有找到协议。我确实检查了我输入http:或https的URL。任何建议将URL传递给我的AsyncTask
//接口方法
@Override
public void displayCityChosen(String cityName) {
Log.i(TAG, "city name= " +cityName);
String weatherURL = "http://www.api.openweathermap.org/data/2.5/weather?q=" + cityName + "&APPID=32c831d8a6937f237acff8eef3d4a58c";
try{
String base = URLEncoder.encode(weatherURL,"UTF-8");
URL finalWeatherURL = new URL(base);
new GetWeather().execute(finalWeatherURL);
}catch (Exception e) {
Log.i(TAG, "ERROR");
}
}
private class GetWeather extends AsyncTask<URL, Void, JSONObject> {
@Override
protected JSONObject doInBackground(URL... urls) {
int statusCode = -1;
String jsonString = "";
for (URL queryURL : urls) {
try {
URLConnection conn = queryURL.openConnection();
jsonString = IOUtils.toString(conn.getInputStream());
jsonResponse = new JSONObject(jsonString);
jsonArray = jsonResponse.getJSONArray("weather");
Log.i(TAG, "Array= " + jsonArray);
break;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonResponse;
}
}
答案 0 :(得分:0)
我认为您还需要一个步骤来将URL更改为HttpURLConnection,我认为这个url不需要对您的使用进行编码。所有编码都搞乱了。
URL url = new URL("http://blah");
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
if (httpURLConnection.getResponseCode() != 200) {
return null;
}
InputStream result = httpURLConnection.getInputStream();
InputStreamReader r = new InputStreamReader(result);
FYI将字符串传递给asynctask并在asynctask中进行所有转换,它将为响应更快的应用程序做出。