问题描述
- 如何断开 HttpURLConnection 的连接?
-
我使用 AsyncTask来连接一个 URLPath:@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.left_list); Button btn = (Button)findViewById(resid); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //how to stop connect } }); new Connecting().execute(); } class Connecting extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); //do something } @Override protected String doInBackground(String... aurl) { 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(); } return null; } @Override protected void onPostExecute(String unused) { super.onPostExecute(unused); //access InputStream is } }
连接期间可能会占用很长时间。
在连接的时候我想设置 点击 Bbutton 按钮来终止 connection 的连接。
如何在 setOnClickListener 方法中设置呢?
解决方案
使用urlConnection的disconnect方法,如果想在外部做disconnect操作,就把urlConnection放在外部初始化完传进来,但是要注意对应关系。
解决方案二:
不是有个disconnect()方法吗?
官方例子
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
}
你只需要在onclick中做disconnect就行了
时间: 2024-10-29 02:36:41