Last active
January 13, 2025 13:25
-
-
Save GrzegorzDyrda/be47602fc855a52fba240dd2c2adc2d5 to your computer and use it in GitHub Desktop.
Kotlin fetch API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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" }""" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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