I am building an app that acquires data from a web service via HttpURLConnection. The app requests data every minute continuously whilst it is open and activated.
At the moment I am opening and closing the connection each time it is required but is it better practise to have a single connection that persists?
The current code is
Expand|Select|Wrap|Line Numbers
- URL url = new URL(tradeURL);
- connection = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
- connection.setRequestProperty("Content-Type", "application/json");
- connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
- connection.setUseCaches(false);
- connection.setDoOutput(true);
- DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
- wr.writeBytes(urlParameters);
- wr.close();
- InputStream is = connection.getInputStream();
- BufferedReader rd = new BufferedReader(new InputStreamReader(is));
- StringBuilder response = new StringBuilder();
- String line;
- while((line = rd.readLine()) != null) {
- response.append(line);
- response.append('\r');
- }
- rd.close();
- connection.disconnect();
Also, is the keep-alive related to the domain level only - ie api.abcd.com - or is the entire url path involved?
Many thanks!