我正在使用: 安道尔工作室。 Okhttp 2.4.0 with AsyncTask。但我无法取消请求。 在Wi-Fi上连接到服务器。如果服务器关闭,那么okHttp会继续尝试连接,我无法取消它。 超时工作正在进行,但我希望在超时之前取消
private OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
执行后我按下api中的特殊取消按钮
public void onCancelClick(View v){
BaseApplication.getInstance().server.cancel();
synchProducts.cancel(true);
}
第一行必须停止okHttp,第二行stoped类扩展AsyncTask
private static final String myTag = "AsyncCall";
public void cancel(){
client.cancel(myTag);
}
AsyncTask类中的backGround
@Override
protected String doInBackground(Void... params) {
publishProgress(1);
String responseStr = sendProductHeaders();
//this performed after timeouts, and spit to my cancel okHttp
publishProgress(2);
if (responseStr != null && !isCancelled()){
ProductsList productsForSend = parseProducts(responseStr);
//correctly stoped thread
我没有忘记在构建器请求中使用.tag
public Response post(String url, String json) {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.tag(myTag)
.url(url)
.post(body)
.build();
return call(request);
}
“call”是我进行okHttp调用的方法
private Response call(Request request){
try {
return client.newCall(request).execute();
} catch (IOException e) {
Log.e("Aync call", "IO exception " + e.getMessage());
}
return null;
}
“标签”为真,okHttp库中的代码真的触发了call.cancel();
for (Call call : executedCalls) {
if (Util.equal(tag, call.tag())) {
call.cancel();
}
}
正在运行Async的方法
public void onRefreshProducts(View v){
progressLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
synchProducts = new SynchProducts(activityCallBack);
synchProducts.execute();
}
“activityCallBack”是我从AsyncTask类调用我的活动时使用的接口 我不想使用okHttp enqueue,但我无法在我的应用程序中插入友好的进度条。 谢谢!