Reading JSON from a RESt API is commonly used - everywhere! It is one of the most used things in computer based communication right now - but it is handled poorly! Especially by Java.
Frameworks
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!
Kotlin - just do what you wanted:
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!
Hello! Your post has been resteemed and upvoted by @ilovecoding because we love coding! Keep up good work! Consider upvoting this comment to support the @ilovecoding and increase your future rewards! ^_^ Steem On!
Reply !stop to disable the comment. Thanks!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Only time can tell what awaits for us in the future!! But we assume that Kotlin’s influence is going to get bigger.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Yeah, I hope this, too! Kotlin is the first JVM language, that really get the right momentum
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit