Skip to content

Instantly share code, notes, and snippets.

@shuantsu
Last active October 4, 2024 18:06
Show Gist options
  • Save shuantsu/16faeada6c2e1416d6a806e59182f475 to your computer and use it in GitHub Desktop.
Save shuantsu/16faeada6c2e1416d6a806e59182f475 to your computer and use it in GitHub Desktop.

KOTLIN + OKHTTP3


Dependency

com.squareup.okhttp3:okhttp:4.12.0

Get

val client = OkHttpClient()
val request = Request.Builder()
    .url("https://g1.globo.com/jogos/static/soletra.json")
    .build()

val webview = findViewById<WebView>(R.id.webview)
webview.loadUrl("file:///android_asset/index.html")
webview.settings.javaScriptEnabled = true
webview.settings.builtInZoomControls = true
webview.settings.displayZoomControls = false

client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        // Handle request failure
        runOnUiThread {
            webview.evaluateJavascript("document.querySelector('main').innerText = 'ERRO'", null);
        }
    }

    override fun onResponse(call: Call, response: Response) {
        // Handle successful response
        response.use {
            if (!response.isSuccessful) throw IOException("Unexpected code $response")

            val responseBody = response.body.string()
            // Process the responseBody (e.g., parse JSON)
            runOnUiThread {
                webview.evaluateJavascript("document.querySelector('main').innerText = render($responseBody)", null);
            }
        }
    }
})

Post

val client = OkHttpClient()

val formBody: RequestBody = MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("message", "heyyyyyyy")
    .addFormDataPart("name", "John Doe")
    .addFormDataPart("age", "42")
    .build()

val request: Request = Request.Builder()
    .url("https://www.filipeteixeira.com.br/phptest/index.php?blah=this_was_sent_via_get")
    .post(formBody)
    .build()

val mainText = findViewById<TextView>(R.id.mainText)

client.newCall(request).enqueue(object : Callback {

    override fun onFailure(call: Call, e: IOException) {
        // Handle request failure
        runOnUiThread {
            mainText.text = "failure T_T"
        }
    }

    override fun onResponse(call: Call, response: Response) {
        // Handle successful response
        response.use {
            if (!response.isSuccessful) throw IOException("Unexpected code $response")

            val responseBody = response.body.string()
            // Process the responseBody (e.g., parse JSON)
            runOnUiThread {
                mainText.text = responseBody
            }
        }
    }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment