如何停止HttpURLConnection.getInputStream()?

10

以下是我的代码:

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;
}
当我上传文件时,代码中的is = connection.getInputStream();这一行会花费很长时间来获取响应。因此,我想实现一个名为stopupload()的停止函数。但是,如果我在代码处理到is = connection.getInputStream();这一行时调用stopupload(),它仍然需要等待响应。
我想要在实现stopupload()时立即停止等待。我该如何做?

1
Thread.interrupt()(编辑:实际上,这可能行不通,因为此API不可中断) - njzk2
有没有不使用线程的方法? - brian
connection = null; is = null; 真的会停止 AsyncTask 的执行吗?我问这个问题是因为 connection = null; 对我不起作用,而且我怀疑 is = null; 也不会奏效,因为 is 只在 getInputStream 结束时被赋值。最终你是否真正获得了想要的结果? - doplumi
3个回答

2
但如果我在代码处理到is = connection.getInputStream();这一行时调用stopupload(),它仍然需要等待回复。

从HoneyComb开始,所有网络操作都不允许在主线程上执行。为了避免出现NetworkOnMainThreadException,您可以使用ThreadAsyncTask

我想在实现stopupload()时立即停止等待。我该怎么做?

以下代码允许用户在2秒后停止上传,但您可以相应地修改睡眠时间(应小于5秒)。

上传:

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...
}

19
这怎么可能成为可接受的解决方案呢?"stopUpload()"没有被实现。 - AsafK

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) {

        }      
     }   
  }

0

按照此处所述,将使用HttpURLConnection的代码包装在一个Future中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接