Pergunta

So right now, I am trying to implement an asynchronous call which calls my BasicHttpClient to get Http response from the internet, when the Http client done its work, it calls one of Callee class's methods.

Generally, my implementation looks like this.

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());
    }
}

The code has been largely simplified, and main() method calls Callee class's getResult() method. btw all of the exceptions has been handled, and send back to callee using callback.

However, the "onRequestFinished" in the Callee class seems like never get called.

Help please.

Foi útil?

Solução 2

Turns out it's because I didn't add all of jars of apache's HttpComponents into my Java Build Path, which causing HttpClient mHttpClient = new DefaultHttpClient() throws out an exception. However, I am using Runnable, so there is no way for me to catch that exception.

Outras dicas

One possibility is that somewhere inside run exception is thrown, so execution flow never reaches call to listener.

By the way, you don't need to create executor on every call, this diminishes executor's advantage of pooling pre-created threads waiting for incoming work. Make executor parameter of BasicHttpClientAsync constructor parameter:

public class Callee implements OnRequestFinishedListener {
      private final ExecutorService executor = Executors.newSingleThreadExecutor();
 ...
      BasicHttpClientAsync httpClient = new BasicHttpClientAsync(this, executor);
 ...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top