JAVA文件
private void getWeatherData(String cityName) throws JSONException {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(WEATHER_API_BASE + API_KEY + TYPE + cityName +OUT_JSON);
Log.e(TAG , sb.toString());
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(TAG, "Error processing Weather API URL", e);
} catch (IOException e) {
Log.e(TAG, "Error connecting to Weather API", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
Log.e(TAG, "in try2");
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray forecastJsonArray = jsonObj.getJSONArray("hourly_forecast");
Log.e(TAG , "Length:" + String.valueOf( forecastJsonArray.length() ));
} catch (Exception e) {
Log.e(TAG, "Cannot process JSON results", e);
}
}
上面的代码适用于其他api,我从中检索JSON,但无法弄清楚为什么它不能用于此。
JSON http://api.wunderground.com/api/73d7d46dcd6153a7/hourly/q/Chandigarh.json
答案 0 :(得分:1)
你如何消费api?你在使用AsyncTask吗?你不能简单地通过调用方法来进行api调用。网络操作需要异步运行。我试过在AsyncTask中运行你的代码,它确实有效。
private class WeatherDataTask extends AsyncTask<String, String, String> {
public WeatherDataTask() {
}
@Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(params[0]);
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e("WeatherTask", "Error processing Weather API URL", e);
} catch (IOException e) {
Log.e("WeatherTask", "Error connecting to Weather API", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return jsonResults.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(null != s){
try {
JSONObject jsonObj = new JSONObject(s);
JSONArray forecastJsonArray = jsonObj.getJSONArray("hourly_forecast");
Log.i("ForeCastJason", forecastJsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
调用此方法类
new WeatherDataTask().execute("http://api.wunderground.com/api/73d7d46dcd6153a7/hourly/q/Chandigarh.json");
答案 1 :(得分:0)
我使用Async Http Client
解决了这个问题