Use OkHttp as HTTP client

This commit is contained in:
2020-09-02 19:45:33 +02:00
committed by Matte23
parent 36bf0059ec
commit bdb3d954fc
2 changed files with 12 additions and 21 deletions

View File

@@ -54,6 +54,7 @@ dependencies {
testImplementation 'junit:junit:4.13' testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test:runner:1.3.0' androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.squareup.okhttp3:okhttp:4.8.1'
implementation 'com.google.code.gson:gson:2.8.6' implementation 'com.google.code.gson:gson:2.8.6'
implementation 'org.jsoup:jsoup:1.13.1' implementation 'org.jsoup:jsoup:1.13.1'
} }

View File

@@ -23,16 +23,17 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import net.underdesk.circolapp.data.Circular import net.underdesk.circolapp.data.Circular
import net.underdesk.circolapp.server.pojo.Response import net.underdesk.circolapp.server.pojo.Response
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.Jsoup import org.jsoup.Jsoup
import java.io.IOException import java.io.IOException
import java.net.URL
import javax.net.ssl.HttpsURLConnection
class DataFetcher { class DataFetcher {
companion object { companion object {
const val ENDPOINT_URL = "https://www.curiepinerolo.edu.it/wp-json/wp/v2/pages/5958" const val ENDPOINT_URL = "https://www.curiepinerolo.edu.it/wp-json/wp/v2/pages/5958"
val gson = Gson() val gson = Gson()
val client = OkHttpClient()
} }
@Throws(IOException::class) @Throws(IOException::class)
@@ -60,29 +61,18 @@ class DataFetcher {
@Throws(IOException::class) @Throws(IOException::class)
private suspend fun retrieveDataFromServer(): String? { private suspend fun retrieveDataFromServer(): String? {
var connection: HttpsURLConnection? = null val request = Request.Builder()
.url(ENDPOINT_URL)
.build()
return withContext(Dispatchers.IO) { return withContext(Dispatchers.IO) {
try { val response = client.newCall(request).execute()
connection = (URL(ENDPOINT_URL).openConnection() as? HttpsURLConnection)
connection?.run {
// Set GET HTTP method
requestMethod = "GET"
setRequestProperty("Accept-Encoding", "none") if (!response.isSuccessful) {
throw IOException("HTTP error code: ${response.code})")
connect()
if (responseCode != HttpsURLConnection.HTTP_OK) {
throw IOException("HTTP error code: $responseCode")
} }
inputStream?.reader()?.readText() response.body?.string()
}
} finally {
// Close Stream and disconnect HTTPS connection.
connection?.inputStream?.close()
connection?.disconnect()
}
} }
} }
} }