Last active
August 29, 2015 14:10
-
-
Save rafayali/c0933ce9a17017065d7a to your computer and use it in GitHub Desktop.
Fetches the data from server and parses it into JSON format.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment