刚接触安卓开发,试着写个小程序熟悉下,就写了天气预报的小程序,通过httpUrlConnection读流的方式来获取网络公共接口提供的天气XML信息。但在建立http连接时一直报java.io.EOFException,多次尝试无过,但正常的httpUrlConnection却能正常访问。
通过查询Baidu大神,比较多的说法是这是由于httpUrlConnection在某些版本的安卓平台所存在的bug问题,果断改之,通过引用httpClinet外部包来解决该问题,非常成功!代码如下:
// http://www.weather.com.cn/data/sk/101010100.html
// http://www.weather.com.cn/data/cityinfo/101010100.html
// http://m.weather.com.cn/data/101010100.html
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity = new BufferedHttpEntity(entity);
InputStream is = entity.getContent();
String jsonStr = convertStreamToString(is);
Log.i("dusss", jsonStr);
JSONObject object = new JSONObject(jsonStr);
JSONObject weatherinfo = object.getJSONObject("weatherinfo");
this.cityId = weatherinfo.getString("cityid");
this.cityName = weatherinfo.getString("city");
this.temp = weatherinfo.getString("temp");
}