2013-05-29 54 views
0

我必须下载一个文件的部分。为此,我使用“xxx.setRequestProperty()”。但是我收到错误,表示在建立连接时无法使用它。所以我想关闭已经使用下载URL建立的连接。如何关闭已建立的网络连接?

try { 

     URL url = new URL(aurl[0]); 
     URLConnection connection = url.openConnection(); 

     InputStream input = new BufferedInputStream(url.openStream()); 
     Log.d(TAG,"connected"); 
     int length = connection.getContentLength(); 

现在我想关闭“连接”。请建议一些方法来做到这一点。

回答

2

你会想在这里你try语句后添加finally块,并呼吁

input.close(); 
connection.disconnect(); 

。您想在finally区块中调用这些代码以确保它们被调用,而不管前面的代码是否失败。

+0

谢谢,它的工作原理。你节省了很多我的时间。 – tet

+0

@tet因为你是新来的,所以请注意 - 如果我的回答(或其他任何人)对你有帮助,请考虑接受它(点击旁边的复选标记)。这样做会给你+2点声望,并增加人们在将来帮助你的可能性:) – drewmoore

2

例子:

InputStream is = null; 
try { 

// Your code here 

} finally { 
    if (is != null) { 
    try { 
     is.close(); 
    } catch (IOException x) { 
     Log.e(TAG, "Excpetion", x); 
    } 
    } 
} 

这样,你将永远关闭的InputStream。 这里是适用于android的javadoc:UrlConnection

相关问题