这是我关于堆栈溢出的第一个问题。通常我可以自己找到答案,但这次我找不到合适的答案。我也是为Android制作应用程序的新手,所以提前抱歉我的noob'nes。
当本地IP地址不可用时,如何在x miliseconds后取消'android java'中的http请求? 我正在使用AsyncTask请求一个html页面。该课程的代码如下。
我现在拥有的是onPreExecute()中定义的定时器,它在X毫秒之后将onCancel()设置为true。 doInBackground()打开一个流等,然后将流写入字符串。
问题是当本地ip地址不可用时,url.openStream()函数会一直运行,直到java.net.ConnectException因为timeOut而启动。我不知道如何使用onCancel()来中断此命令(如果这是可能的话)。
那么如何中断url.openStream命令呢?或者只是终止AsyncTask线程?
private class htmlToString extends AsyncTask<Void,Void,Void> {
public htmlToString asyncObj;
@Override
protected void onPreExecute(){
asyncObj = this;
new CountDownTimer(connectionTimeout, connectionTimeout) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
// stop async task if not in progress
if (asyncObj.getStatus() == AsyncTask.Status.RUNNING) {
asyncObj.cancel(true); // <- how can i cancel the doInBackground with this ?
Log.i("timer", "...still trying to connect...");
}
}
}.start();
}
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(url_string[button_state]);
final InputStream url_inputstream = url.openStream(); // <- if the local ip adress is unavailable, this command keeps running until ETIMEDOUT kicks in
InputStreamReader url_inputstreamreader = new InputStreamReader( url_inputstream );
BufferedReader in = new BufferedReader( url_inputstreamreader );
String inputLine;
while ((inputLine = in.readLine()) != null)
page = page.concat(inputLine);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void params){
// some code
}
}
Edit1:这是在Android Studio 1.5.1中完成的
Edit2:我自己解决了。我只是缩短了java设置的时间。我在doInBackground()中做了这个(代码如下)。这也意味着我可以完全废弃onPreExecute()中的计时器。
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(url_string[button_state]);
URLConnection url_connection = url.openConnection();
url_connection.setConnectTimeout(connectionTimeout); // timout is set here
final InputStream url_inputstream = url_connection.getInputStream();
InputStreamReader url_inputstreamreader = new InputStreamReader( url_inputstream );
BufferedReader in = new BufferedReader( url_inputstreamreader );
String inputLine;
while ((inputLine = in.readLine()) != null)
page = page.concat(inputLine);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
答案 0 :(得分:2)
httpclient.getConnectionManager().shutdown();
答案 1 :(得分:2)
您可以参考以下代码取消请求
httpget.abort();
示例:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class ClientAbortMethod {
public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet(<URL>);
System.out.println("Executing request " + httpget.getURI());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
// Call abort on the request object
httpget.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}