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

Http GET 接口回调

2016-04-20 22:09 295 查看
## 发送http请求,对返回的数据处理 ##

package com.xiaoxu.administrator.myserviceapp.service;

/**
* Created by Administrator on 2016/4/20.
*/

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
* 发送http请求,对返回的数据处理,接口回调
* java回调
*/

public class HttpSendUtil {

/**
* 发送http请求,
* @param address 请求网址
* @param listener
*
* */

/*
* 网络请求属于耗时操作,如果该方法中没有开启线程,那么主线程就会被组塞住
* 如果在该方法中开启一个子线程,子线程获取到的数据将无法返回,
* sendHttpRequest()会在服务器还没来的及响应的时候就执行结束了。这个时候用到java的回调机制
* */

public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {

new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection;

try {

URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection
4000
.setDoOutput(true);

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

StringBuilder response = new StringBuilder();
String line;

while ((line = reader.readLine()) != null) {

response.append(line);
}
if (listener != null) {

listener.onFinish(response.toString());
}

} catch (Exception e) {

if (listener != null) {
listener.onError(e);
}

}
}
}).start();

}

public interface HttpCallbackListener {

/**
*请求成功后的处理
* @param response 服务器返回值
* */
void onFinish(String response);

/**
* 请求异常的处理
* @param e Exception
* */
void onError(Exception e);
}

}


调用方B

private void sendHttp(){

String address = "";//要访问的网址
HttpSendUtil.sendHttpRequest(address, new HttpSendUtil.HttpCallbackListener() {
@Override
public void onFinish(String response) {

//发送成功后的处理,该参数为服务器返回值
}

@Override
public void onError(Exception e) {

//http请求异常的处理
}
});

}


Java回调机制

通常是把一个方法的指针传递给事件源,当某一事件发生时来调用这个方法(也称为“回调”),当然,java中没有指针这个名词,java语言都是通过对象来调用方法的。

如上的HttpSendUtil工具包中,定义了一个接口类,接口的类型作为 sendHttpRequest()的参数传入。在调用方B中调用 A中的方法sendHttpRequest(),并传入该 接口类型的实例,在B中复写了接口中的方法。 这样 在A中 sendHttpRequest()的方法中调用接口中的方法的时候,实际上是用了该接口的对象来调用这些方法。

B 调用 A 的方法,并传入一个接口类型的对象,

在A类中 用B传递进来接口类型的引用 调用 该接口中的抽象方法,

实现了 B 调 A , A 中又调了B。

以上只是我的一点理解,错误请指出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Httpget-回调