我试图在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应该做什么?
答案 0 :(得分:5)
您应该使用SyncHttpClient
代替AsyncHttpClient
。 setUseSynchronousMode
AsyncHttpClient
没有达到预期的效果。
答案 1 :(得分:2)
要使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();