You can use frameworks over frameworks to handle youre API calls for you, but in the end, nothing really gets the job done easily.
When it comes to a basic implementation, one just ends writing the same lines of code again and again:
public String getJsonFromURL(String wantedUrl){
URL url = null;
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
// create the HttpURLConnection
url = new URL(wantedUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here
connection.setRequestMethod("GET");
// uncomment this if you want to write output to this url
//connection.setDoOutput(true);
// give it 15 seconds to respond
connection.setReadTimeout(15 * 1000);
connection.connect();
// read the output from the server
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
what a bunch of code.. just to retrieve a single JSON File from a distant server ... can't there be an easier way? We are in 2018, not in 1994... damn... OH wait!
fun getJsonFromURL(wantedURL: String) : String {
return URL(wantedURL).readText()
}
ok... ffs you should surround this by some try/catch for the malformed URL and / or IOExceptions etc... but at the end, it is a little bit shorter, isn't it?
What do you think of Kotlin?
Easy stuff, or just another hype, that wont last for long?
Comment your oppinion!