public List<String> getMessages() { CLIENT_LOGGER.info("start receiving messages"); checkConnected(); List<String> list = new ArrayList<>(); HttpURLConnection incomeConnection = null; try { CLIENT_LOGGER.info("send request for receive messages"); String query = String.format( "%s?%s=%s", Constants.CONTEXT_PATH, Constants.REQUEST_PARAM_TOKEN, MessageHelper.buildToken(localHistory.size())); URL url = new URL(Constants.PROTOCOL, host, port, query); incomeConnection = prepareInputConnection(url); CLIENT_LOGGER.info("response is received"); String response = MessageHelper.inputStreamToString(incomeConnection.getInputStream()); JSONObject jsonObject = MessageHelper.stringToJsonObject(response); JSONArray jsonArray = (JSONArray) jsonObject.get("messages"); CLIENT_LOGGER.info("received " + jsonArray.size() + " messages"); for (Object o : jsonArray) { logger.info(String.format("Message from server: %s", o)); CLIENT_LOGGER.info("message from server: " + o); list.add(o.toString()); } /** Here is an example how for cycle can be replaced with Java 8 Stream API */ // jsonArray.forEach(System.out::println); // list = (List<String>) // jsonArray.stream().map(Object::toString).collect(Collectors.toList()); } catch (ParseException e) { logger.error("Could not parse message", e); CLIENT_LOGGER.error("could not parse message", e); } catch (ConnectException e) { logger.error("Connection error. Disconnecting...", e); CLIENT_LOGGER.error("connection error", e); disconnect(); } catch (IOException e) { logger.error("IOException occured while reading input message", e); CLIENT_LOGGER.error("IOException occured while reading input message", e); } finally { if (incomeConnection != null) { incomeConnection.disconnect(); } } CLIENT_LOGGER.info("stop receiving messages"); return list; }