本文介绍了如何停止HttpURLConnection.getInputStream()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的code:
私人HttpURLConnection的连接;
私人InputStream为;公共无效上传(){
尝试{
网址URL =新的URL(URLPath);
连接=(HttpURLConnection类)url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(真);
connection.setUseCaches(假);
connection.connect();
是= connection.getInputStream();
}赶上(例外五){
e.printStackTrace();
}
}公共无效stopupload(){
连接= NULL;
是=无效;
}
当我上传的文件,该行是= connection.getInputStream();
会花很多的时间去回复。所以我想实现一个停止功能为 stopupload()
。但是,如果我叫 stopupload()
,而code是在处理行为= connection.getInputStream();
,它仍然需要等待答复。
我要立即停止执行,同时等待 stopupload()
。我该怎么办呢?
解决方案
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
.
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...
}
这篇关于如何停止HttpURLConnection.getInputStream()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!