java - How to close a persistent HTTP Connection without reading -
i have urlconnection want cancel depending on response code without reading data. closely followed android training build following minimal example floods server requests since no connection ever released handle pool reuse
private string downloadurl(string myurl) throws ioexception { inputstream = null; try { url url = new url(myurl); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setreadtimeout(10000 /* milliseconds */); conn.setconnecttimeout(15000 /* milliseconds */); conn.setrequestmethod("get"); conn.setdoinput(true); // starts query conn.connect(); int response = conn.getresponsecode(); log.d(tag, "the response code is: " + response); = conn.getinputstream(); // not read //string contentasstring = readit(is, len); string contentasstring = "notreadinganything"; return contentasstring; } { if (is != null) { is.close(); } } } private class downloadwebpagetask extends asynctask<string, void, string> { @override protected string doinbackground(string... urls) { try { string result = new string(); (int i=0; i<100; i++) { result += downloadurl(urls[0]); } return result; } catch (ioexception e) { return "unable retrieve web page. url may invalid."; } } @override protected void onpostexecute(string result) { log.d(tag, "the response is: " + result); } }
despite docs explicitly stating
but if response body long , not interested in rest of after seeing beginning, can close inputstream
the server reaches maximum number of connections (50) , goes 99% workload if don't read stream works fine if read it. mistake?
edit: failed solution attempts far (thanks @blackbelt of them)
- calling
conn.disconnect()
infinally
block - calling
conn.disconnect()
instead ofis.close()
infinally
block - setting
system.setproperty("http.keepalive", "false");
before first call - setting
conn.setrequestproperty("connection", "close");
before connecting - setting
"{enable_keep_alive", "no"}
on used backend server (civetweb)
you should call disconnect()
too. accordingly documentation
disconnect. once response body has been read, httpurlconnection should closed calling disconnect(). disconnecting releases resources held connection may closed or reused.
inputstream = null; httpurlconnection conn = null; try { url url = new url(myurl); conn = (httpurlconnection) url.openconnection(); } { if (is != null) { is.close(); } if (conn != null) { conn.disconnect(); } }
if still experiencing issues, possible bug backend side
Comments
Post a Comment