Java vs Kotlin - read JSON from URL
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:
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
- TDD - kostet es wirklich Zeit?
- Train...
- Kotlin - work with JSON
- Semux - get your Discord Wallet
- Never Forget!
- South of Bavaria - Sylvensteinsee
- The Hawk
- Java vs Kotlin - read JSON from URL
- ALQO - stake or masternode
- Virtual OTC Trading
- Crypto-Airdrops - Achtung SCAMFALLE!
- Handies: Reparieren als Option - besser als gedacht?
- CRYPTO - Airdrops! get scam-dropped!
- ALQO - update your Nodes and Wallets
- ALQO: on the road again
- Phash is here
- Werde Android-App Developer!
- goodbye findViewById! Hello Kotlin!
- ALQO needs your Baikal!
- ALQO - switch from PoW to PoS struggle