java – 如何使用OKHTTP取消请求
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 如何使用OKHTTP取消请求,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2257字,纯文字阅读大概需要4分钟。
内容图文
我需要能够使用OKHTTP管理一些请求,使用Google Places AutoComplete通过键入地址来接收一些预测.问题是每次我插入一个CHAR它会发出一个新的请求,但同时我需要取消前一个请求!例如:同时纽约市= 13个请求!所以我使用Call的单个实例尝试取消已经请求但没有成功的任何内容.这就是我做的!
Address.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(Address.getText().toString().length() > 3){
_Address = Address.getText().toString();
if(call != null){
call.cancel();
}
Request request = new Request.Builder()
.url(getPlaceAutoCompleteUrl(_Address))
.addHeader("content-type", "application/json")
.addHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; google_sdk Build/MR1) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
.build();
call = client.newCall(request);
call.enqueue(new Callback() {
public void onResponse(Call call, final Response response) throws IOException {
final String result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("Response",result);
PlacePredictions place = null;
try {
place = LoganSquare.parse(result,PlacePredictions.class);
} catch (IOException e) {
e.printStackTrace();
}
if(autoCompleteAdapter == null){
autoCompleteAdapter = new AutoCompleteAdapter(CustomPlaces.this);
recyclerView.setAdapter(autoCompleteAdapter);
autoCompleteAdapter.Add(place.getPlaces());
}else {
autoCompleteAdapter.Clear();
autoCompleteAdapter.Add(place.getPlaces());
autoCompleteAdapter.notifyDataSetChanged();
}
}
});
}
public void onFailure(Call call, IOException e) {
//fail();
}
});
}else {
if(autoCompleteAdapter != null){
autoCompleteAdapter.Clear();
}
}
}
我检查调用对象是否为空并取消请求但仍然继续!
解决方法:
以下内容如何:
//Set tags for your requests when you build them:
Request request = new Request.Builder().
url(url).tag("requestKey").build();
//When you want to cancel:
//A) go through the queued calls and cancel if the tag matches:
for (Call call : mHttpClient.dispatcher().queuedCalls()) {
if (call.request().tag().equals("requestKey"))
call.cancel();
}
//B) go through the running calls and cancel if the tag matches:
for (Call call : mHttpClient.dispatcher().runningCalls()) {
if (call.request().tag().equals("requestKey"))
call.cancel();
}
内容总结
以上是互联网集市为您收集整理的java – 如何使用OKHTTP取消请求全部内容,希望文章能够帮你解决java – 如何使用OKHTTP取消请求所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。