Hej! Od pewnego czasu bawię się w Kotlinie i ostatnio napisałem taki prosty kod do łączenia się z REST Api i prosiłbym o ocenę jego oraz jakieś porady co zmienić by lepiej to wyglądało i działało
Request.kt:
class Request(
private val url : String,
val data : ByteArray?,
val type : RequestType = RequestType.GET,
private val requestFeatures: IRequestFeatures?,
private val headers : HashMap<String, String>?
) : AsyncTask<URL, Long, String>(), IRequest {
private constructor(builder : Builder) : this(
builder.url,
builder.data,
builder.type,
builder.requestFeatures,
builder.headers
)
override fun doInBackground(vararg params: URL?): String {
requestFeatures?.doInBackground()
val httpConnection = URL(url).openConnection() as HttpURLConnection
var finalResponse = ""
try {
when(type) {
RequestType.POST -> httpConnection.requestMethod = "POST"
RequestType.PATCH -> httpConnection.requestMethod = "PATCH"
RequestType.DELETE -> httpConnection.requestMethod = "DELETE"
else -> httpConnection.requestMethod = "GET"
}
httpConnection.addRequestProperty("Content-Type", "application/json")
httpConnection.addRequestProperty("Accept", "application/json")
headers?.forEach {
httpConnection.addRequestProperty(it.key, it.value)
}
finalResponse = streamToString(httpConnection.inputStream)
} catch (e : Exception) {
e.printStackTrace()
} finally {
httpConnection.disconnect()
}
return finalResponse
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
requestFeatures?.onPostExecute(result)
}
override fun toString(): String {
return "Request(url='$url', data=${Arrays.toString(data)}, type=$type)"
}
override fun streamToString(inputStream: InputStream): String {
val bufferReader = BufferedReader(InputStreamReader(inputStream))
var line: String
var result = ""
try {
do {
line = bufferReader.readLine()
if (line != null) {
result += line
}
} while (line != null)
inputStream.close()
} catch (ex: Exception) {
}
return result
}
class Builder {
var url : String = ""
private set
var data : ByteArray? = null
private set
var type : RequestType = RequestType.GET
private set
var requestFeatures : IRequestFeatures? = null
private set
var headers : HashMap<String, String>? = null
fun url(url : String) = apply { this.url = url }
fun data(data : ByteArray) = apply { this.data = data }
fun type(type : RequestType) = apply { this.type = type }
fun requestFeatures(requestFeatures : IRequestFeatures) = apply { this.requestFeatures = requestFeatures }
fun headers(headers : HashMap<String, String>) = apply { this.headers = headers }
fun build() = Request(this)
}
}
IRequest.kt:
interface IRequest {
fun streamToString(inputStream: InputStream) : String
}