Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a http request

Tags:

java

android

This is my very first question on stack overflow. Normally i can find the answers on my own, but this time i can't find a decent answer anywhere. I'm also new at making apps for android, so sorry in advance for my noob'nes.

How do i cancel a http request in 'android java' after x miliseconds when a local IP adress is unavailable? i'm requesting a html page using AsyncTask. The code of the class is given below.

What i have now is the following, a timer defined in the onPreExecute() , which sets the onCancel() to true after X miliseconds. doInBackground() opens a stream etc. and after that it writes the stream to a string.

The problem is that when the local ip adress is unavailable then the url.openStream() function keeps running until java.net.ConnectException kicks in because of a timeOut. I don't know how to interupt this command using onCancel() (if this is even possible).

So how do i interupt the url.openStream command? or just terminate the AsyncTask thread in general?

    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 : This is done in Android Studio 1.5.1

Edit2 : I solved it on my own. I just shortend the timout set by java. I did this in the doInBackground() (code is given below). This also meant that i could completely scrap the timer inside the 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;
    }
like image 214
Malone Avatar asked Feb 01 '16 14:02

Malone


2 Answers

httpclient.getConnectionManager().shutdown();

like image 122
Uroš Hrastar Avatar answered Oct 05 '22 05:10

Uroš Hrastar


you can refer below code for cancel the request

 httpget.abort();

example:

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();
        }
    }

}
like image 44
Musaddique Avatar answered Oct 05 '22 07:10

Musaddique