2026-09-02 23:47:00 +03:00
|
|
|
package agzam.vyatsu.data.remote
|
|
|
|
|
|
|
|
|
|
import android.util.Log
|
|
|
|
|
import kotlinx.coroutines.Dispatchers
|
|
|
|
|
import kotlinx.coroutines.withContext
|
|
|
|
|
import okhttp3.OkHttpClient
|
|
|
|
|
import okhttp3.Request
|
2026-09-11 01:34:05 +03:00
|
|
|
import java.io.InputStream
|
2026-09-02 23:47:00 +03:00
|
|
|
import java.util.concurrent.TimeUnit
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @author Agzam
|
|
|
|
|
*/
|
|
|
|
|
object VyatsuHttpClient {
|
|
|
|
|
|
|
|
|
|
private const val TAG = "HTTP"
|
|
|
|
|
|
|
|
|
|
private val client: OkHttpClient = OkHttpClient.Builder()
|
|
|
|
|
.connectTimeout(15, TimeUnit.SECONDS)
|
|
|
|
|
.readTimeout(30, TimeUnit.SECONDS)
|
|
|
|
|
.build()
|
|
|
|
|
|
|
|
|
|
suspend fun getText(url: String): String = withContext(Dispatchers.IO) {
|
|
|
|
|
client.newCall(Request.Builder().url(url).build()).execute().use { resp ->
|
2026-09-20 03:08:33 +03:00
|
|
|
if (!resp.isSuccessful) Log.e(TAG, "GET $url -> HTTP ${resp.code}")
|
2026-09-02 23:47:00 +03:00
|
|
|
check(resp.isSuccessful) { "HTTP ${resp.code} for $url" }
|
|
|
|
|
resp.body!!.string()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
suspend fun getBytes(url: String): ByteArray = withContext(Dispatchers.IO) {
|
|
|
|
|
client.newCall(Request.Builder().url(url).build()).execute().use { resp ->
|
2026-09-20 03:08:33 +03:00
|
|
|
if (!resp.isSuccessful) Log.e(TAG, "GET $url -> HTTP ${resp.code}")
|
2026-09-02 23:47:00 +03:00
|
|
|
check(resp.isSuccessful) { "HTTP ${resp.code} for $url" }
|
|
|
|
|
resp.body!!.bytes()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 01:34:05 +03:00
|
|
|
/**
|
|
|
|
|
* Открывает потоковое тело ответа. Вызывающий обязан закрыть
|
|
|
|
|
* возвращённый [InputStream], чтобы вернуть соединение в пул.
|
|
|
|
|
*/
|
|
|
|
|
suspend fun openStream(url: String): InputStream = withContext(Dispatchers.IO) {
|
|
|
|
|
val resp = client.newCall(Request.Builder().url(url).build()).execute()
|
2026-09-20 03:08:33 +03:00
|
|
|
if (!resp.isSuccessful) Log.e(TAG, "GET $url -> HTTP ${resp.code}")
|
2026-09-11 01:34:05 +03:00
|
|
|
check(resp.isSuccessful) { "HTTP ${resp.code} for $url" }
|
|
|
|
|
resp.body!!.byteStream()
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 23:47:00 +03:00
|
|
|
}
|