rafayali
11/21/2014 - 10:51 AM

Fetches the data from server and parses it into JSON format.

Fetches the data from server and parses it into JSON format.

/**
	 * A static method which sends request to server by creating
	 * a HTTP connection with provided URL as parameter and converts 
	 * the returned bytes data into readable form.
	 * 
	 * @param parameterUrl
	 * @return {@code List<String>}
	 * @throws Exception
	 */
	public static List<String> queryServer(String parameterUrl) throws Exception{
		String url = "http://localhost:8080";
		URL finalURL;
		finalURL = new URL(url + parameterUrl);
		final HttpURLConnection connection = (HttpURLConnection) finalURL.openConnection();

		connection.setDoOutput(true);
		connection.setRequestMethod("POST");

		final BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		final char[] buffer = new char[Integer.parseInt(connection.getHeaderField("Content-Length"))];
		int bytesread = 0;

		bf.read(buffer, bytesread, buffer.length);

		List<String> finalData = null;

		if(buffer.length > 0){
			JSONArray dataArray = new JSONArray(new String(buffer));
			finalData = new ArrayList<String>(dataArray.length());

			for(int i = 0; i < dataArray.length(); i++){
				finalData.add((String) dataArray.get(i));
			}
		}
		
		connection.disconnect();

		return finalData;
	}