How to stop HttpURLConnection.getInputStream()?

旧巷老猫 提交于 2019-12-10 12:49:47

问题


Below is my code:

private HttpURLConnection connection;
private InputStream is;

public void upload() {
    try {
        URL url = new URL(URLPath);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.connect();
        is = connection.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void stopupload() {
    connection = null;
    is = null;
}

When I upload file, the line is = connection.getInputStream(); will spend a lot of time to get reply. So I want to implement a stop function as stopupload(). But if I call stopupload() while the code is handling at line is = connection.getInputStream();, it still needs to wait for its reply.

I want to stop waiting at once while implement stopupload(). How can I do it?


回答1:


But if I call stopupload() while the code is handling at line is = connection.getInputStream();, it still needs to wait for its reply.

Starting from HoneyComb, all network operations are not allowed to be executed over main thread. To avoid getting NetworkOnMainThreadException, you may use Thread or AsyncTask.

I want to stop waiting at once while implement stopupload(). How can I do it?

Below code gives the user to stop uploading after 2 seconds, but you can modify the sleep times (should be less than 5 seconds) accordingly.

upload:

public void upload() {
    try {
        URL url = new URL(URLPath);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.connect();
        // run uploading activity within a Thread
        Thread t = new Thread() {
            public void run() {
                is = connection.getInputStream();
                if (is == null) {
                    throw new RuntimeException("stream is null");
                }
                // sleep 2 seconds before "stop uploading" button appears
                mHandler.postDelayed(new Runnable() {
                    public void run() {
                        mBtnStop.setVisibility(View.VISIBLE);
                    }
                }, 2000);
            }
        };
        t.start();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
}

onCreate:

@Override
public void onCreate(Bundle savedInstanceState) {
    // more codes...
    Handler mHandler = new Handler();
    mBtnStop = (Button) findViewById(R.id.btn_stop);
    mBtnStop.setBackgroundResource(R.drawable.stop_upload);
    mBtnStop.setOnClickListener(mHandlerStop);
    mBtnStop.setVisibility(View.INVISIBLE);

    View.OnClickListener mHandlerStop = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopUpload(); // called when "stop upload" button is clicked
        }
    };

    // more codes...
}



回答2:


private HttpURLConnection connection;
private InputStream is;

   public void upload() {
       try {
    URL url = new URL(URLPath);
    connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.connect();

    Thread t = new Thread() {
        public void run() {
             is = connection.getInputStream();                
        }
    };
    t.start()
} catch (Exception e) {
    e.printStackTrace();
}catch (InterruptedException e) {
        stopupload(connection ,is, t);
    }      
}

public void stopupload(HttpURLConnection connection ,InputStream  is,Thread t) {
  if(connection != null ){
    try {
           t.interupt();
               running = false;
               connection=null;
           is=null;
        } catch (Exception e) {

        }      
     }   
  }



回答3:


Wrap the code that uses HttpURLConnection inside a Future, as described here.



来源:https://stackoverflow.com/questions/15380993/how-to-stop-httpurlconnection-getinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!