Skip to content

Instantly share code, notes, and snippets.

@GrzegorzDyrda
Last active January 13, 2025 13:25
Show Gist options
  • Save GrzegorzDyrda/be47602fc855a52fba240dd2c2adc2d5 to your computer and use it in GitHub Desktop.
Save GrzegorzDyrda/be47602fc855a52fba240dd2c2adc2d5 to your computer and use it in GitHub Desktop.
Kotlin fetch API
import java.net.HttpURLConnection
import java.net.URL
/**
* Sends an HTTP request to the given [url], using the given HTTP [method]. The request can also
* include custom [headers] and [body].
*
* Returns the [Response] object containing [statusCode][Response.statusCode],
* [headers][Response.headers] and [body][Response.body].
*/
fun sendRequest(url: String, method: String = "GET", headers: Map<String, String>? = null, body: String? = null): Response {
val conn = URL(url).openConnection() as HttpURLConnection
with(conn) {
requestMethod = method
doOutput = body != null
headers?.forEach(this::setRequestProperty)
}
if (body != null) {
conn.outputStream.use {
it.write(body.toByteArray())
}
}
val responseBody = conn.inputStream.use { it.readBytes() }.toString(Charsets.UTF_8)
return Response(conn.responseCode, conn.headerFields, responseBody)
}
data class Response(val statusCode: Int, val headers: Map<String, List<String>>? = null, val body: String? = null)
//
// Obtaining data via GET request
//
val response = sendRequest(
url = "https://jsonplaceholder.typicode.com/posts/1"
)
println(response.statusCode)
println(response.headers)
println(response.body)
//
// Updating data via POST request
//
sendRequest(
url = "https://jsonplaceholder.typicode.com/posts/1",
method = "POST",
headers = mapOf(
"Content-Type" to "application/json"
),
body = """{ "title": "Sample title", "body": "Sample body" }"""
)
@imtheaman
Copy link

getting Error : java.io.FileNotFoundException: {my server url}, is there any possibility that it's throwing error in the process of reading or writing the stream? @GrzegorzDyrda

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment