Posts

Showing posts with the label Httpurlconnection

Android With Kotlin - How To Use HttpUrlConnection

Answer : Here is a simplification of the question and answer. Why does this fail? val connection = HttpURLConnection() val data = connection.inputStream.bufferedReader().readText() // ... do something with "data" with error: Kotlin: Cannot access '': it is 'protected/ protected and package /' in 'HttpURLConnection' This fails because you are constructing a class that is not intended to directly be constructed. It is meant to be created by a factory, which is in the URL class openConnection() method. This is also not a direct port of the sample Java code in the original question. The most idiomatic way in Kotlin to open this connection and read the contents as a string would be: val connection = URL("http://www.android.com/").openConnection() as HttpURLConnection val data = connection.inputStream.bufferedReader().readText() This form will auto close everything when done reading the text or on an exception. If you...