我试图在loopj上使用setUseSynchronousMode来等待http调用的结果,然后在一种情况下继续。我试着:
AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
Log.d("TEST", "Got results");
}
};
AsyncHttpClient client = new AsyncHttpClient();
responseHandler.setUseSynchronousMode(true);
client.get("http://www.google.com", responseHandler);
Log.d("TEST", "Don't want to get here until after getting results");
但是结果是:
07-11 19:48:05.631 D/TEST﹕ Don't want to get here until after getting results
07-11 19:48:05.814 D/TEST﹕ Got results
我是否误解了setUseSynchronousMode应该做什么?
您应该使用SyncHttpClient
而不是AsyncHttpClient
。setUseSynchronousMode
对AsyncHttpClient
没有预期的效果
为了使AsyncHttpClient
的同步版本具有取消它的能力,我在主线程上做所有事情。以前我在AsyncTask
中运行它,一旦AsyncHttpClient.post()
被调用,AsyncTask
就会完成,我无法跟踪AsyncHttpClient
实例。
SyncHttpClient
不允许我取消上传,所以我知道我必须使用AsyncHttpClient
并进行适当的更改。
下面是我上传一个使用AsyncHttpClient
并允许取消的文件的类:
public class AsyncUploader {
private String mTitle;
private String mPath;
private Callback mCallback;
public void AsyncUploader(String title, String filePath, MyCallback callback) {
mTitle = title;
mPath = filePath;
mCallback = callback;
}
public void startTransfer() {
mClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
File file = new File(mPath);
try {
params.put("title", mTitle);
params.put("video", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mClient.setTimeout(50000);
mClient.post(mContext, mUrl, params, new ResponseHandlerInterface() {
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
// TODO convert instream to JSONObject and do whatever you need to
mCallback.uploadComplete();
}
}
@Override
public void sendProgressMessage(int bytesWritten, int bytesTotal) {
mCallback.progressUpdate(bytesWritten, bytesTotal);
}
@Override
public void sendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
mCallback.failedWithError(error.getMessage());
}
});
}
/**
* Cancel upload by calling this method
*/
public void cancel() {
mClient.cancelAllRequests(true);
}
}
你可以这样运行它:
AsyncUploader uploader = new AsyncUploader(myTitle, myFilePath, myCallback);
uploader.startTransfer();
/* Transfer started */
/* Upon completion, myCallback.uploadComplete() will be called */
取消上传,只需调用cancel()
:
uploader.cancel();