java - HttpURLConnection Closing IO Streams -
i new java , httpurlconnection. should close opened io streams before dropping connection. if close streams, should need drop connection well? proper way of implementation?
try { string uri = "http://localhost:8081/resteasy/saju/post/text"; url url = new url(uri); connection = (httpurlconnection) url.openconnection(); connection.setrequestmethod("post"); connection.setrequestproperty("accept", "text/plain"); connection.setrequestproperty("content-type", "text/plain"); connection.setdooutput(true); outputstream os = connection.getoutputstream(); //bla bla system.out.println(connection.getresponsecode()); inputstream istream = connection.getinputstream(); //bla bla } catch (malformedurlexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); }finally{ // os.close(); - required // istream.close(); - required connection.disconnect(); } }
you should call close()
on input/output/error streams when finished using them.
disconnect more complicated. according javadoc disconnect()
:
"indicates other requests server unlikely in near future."
this recognizing fact http 1.1 spec has "persistent connection" feature allows same tcp/ip connection used in sequence of requests same server. (this happens transparently.) when call disconnect
, taken hint close connection.
so resource , performance perspective:
- it idea call
disconnect
if aren't send request same server, - it bad idea if request in near future.
Comments
Post a Comment