For the time being I am using AsyncHttpClient to call RESTfull WebService from android Device and it is running fine. I want to optimize it using FutureTask as it allows us to check if a thread is finished and stuff. The code I am using now is something like this
AsyncHttpClient client = new AsyncHttpClient();
try {
client.post(applicationContext, "http://" + ip
+ ":8080/MyWebService/jaxrs/service/getData",
new StringEntity("String"), "application/json",
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
}
@Override
public void onFailure(Throwable e, String content) {
System.err.println("Exception: "
+ e.getMessage());
}
});
} catch (Exception e) {
System.err.println("Exception: "
+ e.getMessage());
}
What I know is to make AsyncHttpClient inside call function of Callable < class >, to call WebService.
Here I am confused as AsyncHttpClient is also running in a thread. How should I call Web Service using Future.
NOTE: - Beginner in Threading.
Future + HttpClient = AsyncHttpClient
If AsyncHttpClient.onSuccess() or AsyncHttpClient.onFailure() is called, it means the thread is finished, or it's still running(blocked).
==EDIT==
Ok, an example here. Please read more about FutureTask and Executor in java doc.
FutureTask<HttpResult> future = new FutureTask<HttpResult>(new Callable<HttpResult>() {
// GET A HTTP RESULT IN ANOTHER THREAD
@Override
public HttpResult call() throws Exception {
HttpClient httpClient =new HttpClient();
//set url, http method and params
HttpResult result = httpClient.getResult(); // sync request, it costs a long time.
return result;
}
}){
// FutureTask.DONE() WILL BE CALLED ASYNCHRONOUSLY
@Override
protected void done() {
try {
HttpResult result=get();
//read the result
} catch (InterruptedException e) {
logger.error("", e);
} catch (ExecutionException e) {
logger.error("", e);
}
}
};