差異處
這裏顯示兩個版本的差異處。
java:basic:urlconnection [2018/09/25 09:58] tony [How to?] |
java:basic:urlconnection [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>java}} | ||
- | ====== URLConnection ====== | ||
- | ===== Problem ===== | ||
- | URL的openStream與URLConnection的getLastModified後將會有兩個連線,如果是在有連線數限制的伺服器上,將會造成問題。 | ||
- | <code java> | ||
- | 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); | ||
- | } | ||
- | } | ||
- | </code> | ||
- | ===== How to? ===== | ||
- | 最簡單作法就是重複使用URLConnection所建立出來的連線: | ||
- | <code java> | ||
- | 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); | ||
- | } | ||
- | } | ||
- | </code> | ||
- | 另一個方法就是避免URL的openStream與URLConnection的操作同時使用即可。在連線的釋放,我是直接close InputStream;假如有cast為HttpURLConnection可以使用disconnect。 | ||
- | ===== Refernce ===== | ||
- | * [[http://kingori.co/minutae/2013/04/httpurlconnection-disconnect/|Do we need to call HttpURLConnection.disconnect()?]] | ||
- | * [[http://stackoverflow.com/questions/9150200/closing-urlconnection-and-inputstream-correctly|Closing URLConnection and InputStream correctly?]] | ||
- | ===== ===== | ||
- | ---- | ||
- | \\ | ||
- | ~~DISQUS~~ |