《第一行代码》中获取天气的方法已经不行了,天气老是不更新。。。搞了大半天,现在终于搞定了。
一。数据来源
http://wthrcdn.etouch.cn/weather_mini?city=北京
通过城市名字获得天气数据,json数据
http://wthrcdn.etouch.cn/weather_mini?citykey=101010100
通过城市id获得天气数据,json数据
获得JSON的数据为:
{"desc":"OK","status":1000,"data":{"wendu":"19","ganmao":"昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。","forecast":[{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 25℃","type":"晴","low":"低温 8℃","date":"14日星期二"},{"fengxiang":"北风","fengli":"5-6级","high":"高温 26℃","type":"阴","low":"低温 12℃","date":"15日星期三"},{"fengxiang":"北风","fengli":"4-5级","high":"高温 20℃","type":"多云","low":"低温 7℃","date":"16日星期四"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 23℃","type":"晴","low":"低温 10℃","date":"17日星期五"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 20℃","type":"阴","low":"低温 10℃","date":"18日星期六"}],"yesterday":{"fl":"3-4级","fx":"北风","high":"高温 18℃","type":"晴","low":"低温 5℃","date":"13日星期一"},"aqi":"86","city":"北京"}}
按照道理,接下去应该比较容易了,只需要对json数据解析,然后获取自己想要的数据就可以了,但是通过httpclient或者volley获取到的都是乱码,设置utf-8也没用,接下去就要解决乱码的问题
二.乱码解决
这里我用的是Volley,附上郭大神的博客地址http://blog.csdn.net/guolin_blog/article/details/17482165
乱码解决,需要重写parseNetworkResponse方法,具体如下:
RequestQueue requestQueue=Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
Log.e("dd", response.toString());
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
})
{
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)
{
JSONObject jsonObject;
try {
jsonObject = new JSONObject(new String(response.data,"UTF-8"));
return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return Response.error(new ParseError(e));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return Response.error(new ParseError(e));
}
}
};
requestQueue.add(jsonObjectRequest);
三。收工,附上截图
PS:我用完之后是这个样子,你用完之后也是这个样子,没有特技。:)