Phash avatar

Java vs Kotlin - read JSON from URL

phash

Published: 03 Sept 2018 › Updated: 03 Sept 2018Java vs Kotlin - read JSON from URL

Java vs Kotlin - read JSON from URL

IJava vs Kotlin 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!

Leave Java vs Kotlin - read JSON from URL to:

Written by

Read more #programming posts


Best Posts From Phash

We have not curated any of phash's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Phash