新线程网络请求,回调方法在主线程中进行
2016-01-07 14:12
513 查看
新建HttpUtil类
写出其中的Http请求方法sendHttpRequest,定义回调接口。
现在onComplete和onError方法是在新开线程总执行的,不能进行更新UI等一系列操作,所以需要我们新建方法requestInMainThread方法,让回调能在主线程中进行:
end.
写出其中的Http请求方法sendHttpRequest,定义回调接口。
public class HttpUtil { public static void sendHttpRequest(final String address,final HttpCallbackListenner listener){ new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub HttpURLConnection connection=null; try { URL url=new URL(address); connection=(HttpURLConnection) url.openConnection(); connection.setReadTimeout(8000); connection.setConnectTimeout(8000); connection.setRequestMethod("GET"); InputStream is=connection.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(is)); String str; StringBuilder response=new StringBuilder(); while((str=reader.readLine())!=null){ response.append(str); } if(listener!=null){ listener.onComplete(response.toString()); } } catch (Exception e) { // TODO Auto-generated catch block if(listener!=null) listener.onError(e); } finally{ if(connection!=null) connection.disconnect(); } } }).start(); } public interface HttpCallbackListenner{ void onComplete(String response); void onError(Exception e); } }
现在onComplete和onError方法是在新开线程总执行的,不能进行更新UI等一系列操作,所以需要我们新建方法requestInMainThread方法,让回调能在主线程中进行:
private Handler handler = new Handler(Looper.getMainLooper()); public void requestInMainLooper(String address,final HttpCallbackListenner listener) { sendHttpRequest(address, new HttpCallbackListenner() { @Override public void onComplete(final String response) { handler.post(new Runnable() { @Override public void run() { listener.onComplete(response); } }); } @Override public void onError(final Exception e) { handler.post(new Runnable() { @Override public void run() { listener.onError(e); } }); } }); }
end.
相关文章推荐
- 网络通信协议笔记
- 西安鹏程张建宁老师主讲网络安全
- 基于C#的socket编程的TCP异步实现
- COMODO反间谍软件BOClean在线下载
- 页面自动跳转与http302、html refresh以及js跳转之间的关系
- iOS状态栏获取网络类型,运营商,电池电量,显示的系统时间等信息
- Java web开发(3)——Http
- StringHttpMessageConverter 乱码问题
- Spring Http Basic(基本)和Digest(摘要)验证
- 使用HttpFileServer自建下载服务器
- 令牌桶算法和漏桶算法
- 对TCP连接被重置解决方案的探究
- get,post 区别,HTTP通信
- QIODevice (Qt中所有 I/O devices 的基类,QFile,QBuffer,QTcpSocket等)
- python操作网络图片
- Linux tcpdump命令详解
- 一个定期翻译国外Android优质的技术、开源库、软件架构设计、测试等文章的开源项目 http://www.devtf.cn
- 轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求
- 白话网络技术点
- 友善之臂开发板启动脚本配置以及fa-network-service后台服务对网络的配置