這是本文件的舊版!


URLConnection

URL的openStream與URLConnection的getLastModified後將會有兩個連線,如果是在有連線數限制的伺服器上,將會造成問題。

public static void main(String[] args) {
	InputStream is = null;
	try {
		URL url = new URL("http://10.134.15.15/test.txt");
		URLConnection urlConn = url.openConnection();
		System.out.println(urlConn.getLastModified());
		is = url.openStream();
		// some operations
 
	} catch (Exception e) {
		logger.error("", e);
	} finally {
		Cleaner.close(is);
	}
}

最簡單作法就是直接使用URLConnection的getInputStream:

public static void main(String[] args) {
	InputStream is = null;
	try {
		URL url = new URL("http://10.134.15.15/test.txt");
		URLConnection urlConn = url.openConnection();
		System.out.println(urlConn.getLastModified());
		is = urlConn.getInputStream();
		// some operations
	} catch (Exception e) {
		logger.error("", e);
	} finally {
		Cleaner.close(is);
	}
}
另一個方法就是避免URL的openStream與URLConnection的操作同時使用即可。在連線的釋放,我是直接close InputStream;假如有cast為HttpURLConnection可以使用disconnect。