您的位置:首页 > 理论基础 > 计算机网络

Android笔记 httpurlconnection

2016-05-10 15:01 363 查看
//获得天气信息的线程,网络连接是耗时任务,将其放到子线程中执行,通过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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: