所以现在,我正在尝试实现一个异步调用,它调用我的 BasicHttpClient 从互联网获取 Http 响应,当 Http 客户端完成其工作时,它调用 Callee 类的方法之一。
一般来说,我的实现是这样的。
public class BasicHttpClientAsync {
private OnRequestFinishedListener mListener;
public interface OnRequestFinishedListener {
public void onRequestFinished(HttpResponse httpResponse);
public void onRequestFinished(ClientProtocolException e);
public void onRequestFinished(IOException e);
}
public BasicHttpClient(OnRequestFinishedListener listener) {
this.mListener = listener;
}
private Runnable task = new Runnable() {
@override
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse httpResponse = httpClient.execute(httpGet);
mListener.onRequestFinished(httpResponse);
}
};
public void getResponse() {
ExecutorService executor = Executors.newSingleThreadExecutor();
FuturkTask<?> futureTask = new FutureTask<Object>(task, null);
executor.execute(futureTask);
}
}
public class Callee implements OnRequestFinishedListener {
public void getResult() {
BasicHttpClientAsync httpClient = new BasicHttpClientAsync(this);
httpClient.getResponse();
}
@override
public void onRequestFinished(HttpResponse httpResponse) {
System.out.println(httpResponse.toString());
}
}
代码已大大简化,main() 方法调用 Callee 类的 getResult() 方法。顺便说一句,所有异常都已处理,并使用回调发送回被调用者。
但是,Callee 类中的“onRequestFinished”似乎永远不会被调用。
请帮忙。