//获得天气信息的线程,网络连接是耗时任务,将其放到子线程中执行,通过handler传递消息更新ui
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
//可传入区号,城市名的中英文
String cityId = WebTools.parseCityCode("北京");
URL url = new URL("https://api.heweather.com/x3/weather?cityid="+cityId+"&key=e3f23e2cb8c54227abe6927833799526");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
Message message = new Message();
message.what = 00111;
message.obj = sb.toString();
handler.sendMessage(message);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection != null){
connection.disconnect();
}
}
}
}).start();
Android笔记 httpurlconnection
最新推荐文章于 2017-02-07 16:48:59 发布