android网络编程中使用java的回调机制

1) 先定义一个接口

public interface HttpCallbackListener {
    void onFinish(String response);
    void onError(Exception e);
}

2) 在工具类HttpUtil中定义一个静态方法sendHttpReq()

static void sendHttpReq(final String address, final HttpCallbackListener listener){
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection connection = null;
            StringBuilder builder = null;
            try {
                URL url = new URL(address);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.connect();//要在清单文件中声明连接网络的权限
                if (200 == connection.getResponseCode()){
                    Log.e("lyl", "连接成功");
                    InputStream is = connection.getInputStream();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String line = null;
                    builder = new StringBuilder();
                    while ((line = reader.readLine()) != null){
                        builder.append(line);
                    }
                }

                Log.e("lyl", "builder : " + builder.toString());
                if ((null != builder.toString()) && (null != listener)){
                    listener.onFinish(builder.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (null != listener){
                    listener.onError(e);
                }
            } finally {
            if (null != connection){
                connection.disconnect();
                connection = null;
            }
        }
    }
}).start();

开启子线程发起http请求,服务器响应的数据传入HttpCallbackListener的onFinish()方法

3) 传入url,在UI线程中更新出来得到的数据

HttpUtil.sendHttpReq("https://www.baidu.com/", new HttpCallbackListener() {
	@Override
	public void onFinish(final String res) {
		Log.e("lyl", "onFinish: " + res);
		//要开启UI线程进行view更新,否则会报错:
		//Only the original thread that created a view hierarchy can touch its views.
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				tv_text.setText(res);
			}
		});
	}
	@Override
		public void onError(Exception e) {
	}
});

4) 使用Okhttp:

//在build.gradle中添加依赖 compile 'com.squareup.okhttp3:okhttp:3.7.0'
static void sendOkHttpReq(String add, okhttp3.Callback callback){
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(add)
            .build();
    client.newCall(request).enqueue(callback);
}

HttpUtil.sendOkHttpReq("https://www.baidu.com/", new okhttp3.Callback() {
    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_text.setText(response.toString());
            }
        });
    }
    @Override
    public void onFailure(Call call, IOException e) {
    }
});

在okhttp3.Callback接口中定义了

void onFailure(Call call, IOException e);
void onResponse(Call call, Response response) throws IOException;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值