added a wrapper for the okhttp Response

This commit is contained in:
Arjix 2021-10-02 23:54:16 +03:00 committed by GitHub
parent 15c1316b1f
commit ea537da831
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -16,6 +16,63 @@ private val DEFAULT_COOKIES: Map<String, String> = mapOf()
private val DEFAULT_REFERER: String? = null
// lowercase to avoid conflicts
class response(response: Response) {
companion object {
private var responseText: String? = null
private var responseBody: ResponseBody? = null
}
public val rawResponse: Response = response
val text: String
get() {
if (responseText != null) return responseText!!
if (responseBody == null) responseBody = rawResponse.body
responseText = responseBody.toString()
return responseText!!
}
val body: ResponseBody
get() {
if (responseBody == null) responseBody = rawResponse.body
return responseBody!!
}
val url: String
get() {
return rawResponse.request.url.toString()
}
val cookies: Map<String, String>
get() {
val cookieList =
rawResponse.headers.filter { it.first.equals("set-cookie", ignoreCase = true) }.getOrNull(0)?.second?.split(";")
return cookieList?.associate {
val split = it.split("=")
(split.getOrNull(0)?.trim() ?: "") to (split.getOrNull(1)?.trim() ?: "")
}?.filter { it.key.isNotBlank() && it.value.isNotBlank() } ?: mapOf()
}
val headers: Headers
get() {
return rawResponse.headers
}
val ok: Boolean
get() {
return rawResponse.isSuccessful
}
val status: Int
get() {
return rawResponse.code
}
}
/** WARNING! CAN ONLY BE READ ONCE */
val Response.text: String
get() {
@ -98,7 +155,7 @@ fun get(
.build()
val request = getRequestCreator(url, headers, referer, params, cookies, cacheTime, cacheUnit)
return client.newCall(request).execute()
return response(client.newCall(request).execute())
}
@ -120,7 +177,7 @@ fun post(
.callTimeout(timeout, TimeUnit.SECONDS)
.build()
val request = postRequestCreator(url, headers, referer, params, cookies, data, cacheTime, cacheUnit)
return client.newCall(request).execute()
return response(client.newCall(request).execute())
}
@ -156,4 +213,4 @@ fun postRequestCreator(
.headers(getHeaders(headers, referer, cookies))
.post(getData(data))
.build()
}
}