- Kotlin HTTP GET/POST request
- HTTP GET
- HTTP POST
- Kotlin GET request with HttpClient
- GET query parameters with HttpClient
- Kotlin POST JSON data request with HttpClient
- Kotlin POST FORM data request with HttpClient
- Kotlin GET request with Fuel
- GET query parameters with Fuel
- Kotlin POST JSON data request with Fuel
- Kotlin POST FORM data request with Fuel
- Use Ktor for networking
- Connect Ktor
- Set up an HTTP client
- Select an engine
- Mock engine
- Configure the client
- Engine configuration
- Features
- Create HTTP requests
- Method
- Headers
- Response type
- Multipart requests
- Concurrency
- Close the HTTP client
- How to use Ktor client on Android
- Walking to Kotlin multiplatform using Ktor Client
Kotlin HTTP GET/POST request
last modified January 26, 2021
Kotlin HTTP GET/POST request tutorial shows how to send a GET and a POST request in Kotlin. We use HttpClient and Fuel library.
The is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.
In the examples, we use httpbin.org , which is a freely available HTTP request and response service, and the webcode.me , which is a tiny HTML page for testing.
HTTP GET
The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
HTTP POST
The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.
Kotlin GET request with HttpClient
HttpClient is a tool for generating http requests in Java.
We create a GET request to the webcode.me webpage.
A client is created.
We build a synchronous request to the webpage. The default method is GET.
We send the request, retrieve the content of the response, and print it to the console.
This is the output.
GET query parameters with HttpClient
The following example appends some query parameters to the URL.
We create a GET request to the httpbin.org/get with some URL parameters.
This is a string extension method for encoding URL paramaters.
We have a map of values. We endcode them for the URL path with the custom extension method.
We append the parameters to the URL.
This is the output.
Kotlin POST JSON data request with HttpClient
The following example sends a POST request with HttpClient. The data is sent in JSON format.
For this example, we need the jackson-module-kotlin dependency.
We generate a POST request to the httpbin.org/post webpage. The post data are taken from a map and transformed into a string with Jackson’s ObjectMapper.
A POST request is generated via the POST method.
This is the output.
Kotlin POST FORM data request with HttpClient
With application/x-www-form-urlencoded the data is sent in the body of the request; the keys and values are encoded in key-value tuples separated by ‘&’, with a ‘=’ between the key and the value.
We generate a POST request with FORM data to httpbin.org/post .
We set the content type header to application/x-www-form-urlencoded .
With the String.uft8 and formData helper functions, we create a body publisher with url encoded values.
This is the output.
Kotlin GET request with Fuel
Fuel is an easy-to-use HTTP networking library for Kotlin.
We need to add the fuel dependency.
The example sends a simple GET request to webcode.me .
GET query parameters with Fuel
The following example sends some query parameters with the GET request.
The Fuel library automatically takes care of encoding the parameters in httpGet .
Kotlin POST JSON data request with Fuel
We set a POST request with JSON data. This time we use the Gson library.
We have additional dependencies for the Gson library.
We serialize the user object into a JSON string with the toJson method. We set a JSON body with the jsonBody method.
Kotlin POST FORM data request with Fuel
In the following example, we send a POST request with FORM data.
Fuel automatically tranforms the data to application/x-www-form-urlencoded content type in httpPost .
Источник
Use Ktor for networking
Conventionally, modern applications with client-server architecture use the HTTP protocol for transferring data between the server and the client. If your mobile app has a server to exchange data with, an HTTP client is an essential part of this app that enables its interaction with the server.
For Kotlin projects, we recommend Ktor- a framework for building asynchronous clients and servers. It’s written in Kotlin and leverages its core features such as coroutines or targeting multiple platforms. For more detailed information, see the Ktor website.
In Kotlin Multiplatform Mobile (KMM) projects, you can use the Ktor Http Client for interactions with servers. On this page, we’ll take a brief tour on how to connect the Ktor client to a KMM project, create and configure an HTTP client, and perform network requests with it.
Connect Ktor
To use the Ktor HTTP client in your project, connect the client as a Gradle dependency: add the corresponding entries in the dependencies block of a module’s build file ( build.gradle or build.gradle.kts ).
Ktor provides separate artifacts for using the HTTP client: a common module and different engines that process the network request.
To use Ktor KMM module in the common code, add the dependency to io.ktor:ktor-client-core to the commonMain source set in the build.gradle or build.gradle.kts file of the KMM module:
Then connect the platform engines by adding the dependencies on them. For Android, add the ktor-client-android dependency to the corresponding source set:
For iOS, add the ktor-client-ios dependency to the corresponding source set:
Instead of $ktor_version , use the required version of the library.
For more information about connecting the Ktor client to the multiplatform project, see the Ktor documentation.
Set up an HTTP client
In Ktor, HTTP clients are represented by the HttpClient class. To create an HTTP client with default settings, call the HttpClient() constructor:
CIO here is the class that represents an HTTP engine that the client will use. Let’s take a closer look at the available HTTP engines.
Select an engine
Ktor offers you multiple HTTP engines to use in your project: Apache, CIO, Android, iOS, and others. Engines differ by sets of supported features or platforms they work on. For the full list of supported HTTP engines, refer to the Ktor documentation.
To use a specific HTTP engine, connect the corresponding Ktor artifact as a dependency, for example:
Now you can create an HTTP client with this engine: just pass the engine class as an argument of the HttpClient() constructor.
If you call the HttpClient() constructor without an argument, then one of the engines available to Ktor will be automatically selected at compile time.
Mock engine
Ktor offers a special HTTP engine for testing purposes — MockEngine , which simulates HTTP calls without an actual connection to an API endpoint.
There are several platform-specific implementations of MockEngine . To use them in your KMM project, connect the corresponding dependencies: io.ktor:ktor-client-mock-jvm for Android io.ktor:ktor-client-mock-native for iOS
Then create an HttpClient instance with MockEngine :
For detailed information about testing with Ktor, refer to the Ktor documentation.
Configure the client
Client configuration can be done through a lambda expression with the receiver. In other words, the receiver object of the HttpClientConfig class for a specific HTTP engine through which the entire configuration is performed will be transferred to the lambda, which is transferred as an argument to the HttpClient() function.
To configure the client, pass a lambda expression to the HttpClient() call.
In this example, the following configuration is used: Receiving HTTP errors in response don’t cause exceptions A ResponseObserver is created that prints response statuses to the standard output.
Engine configuration
When you create an HTTP client with a specific engine, pass the engine configuration in the same lambda in the engine block.
For more information on engines configuration, see the Ktor documentation.
Features
Ktor lets you use additional HTTP client functionality ( features) that is not available by default, for example, logging, authorization, or serialization. Most of them are distributed in separate artifacts. To use them, you should connect them as dependencies to the common source set. For example:
Then, add the required features in the client configuration using the install() function.
For example, you can use the ResponseObserver class to set up an observer for responses. At the beginning of the article, an observer was added using the ResponseObserver<> builder function, which internally calls up the install function. An observer as additional functionality can be explicitly added as follows:
For the full list of available HTTP client features and instructions on their configuration, see the Ktor documentation.
Create HTTP requests
The main function for creating HTTP requests is request — an extension function for the HttpClient class. All the request settings are generated using the HttpRequestBuilder class. The request function has the suspend modifier, so requests can be executed in coroutines. For detailed information about creating and sending requests with the Ktor client, see the Ktor documentation.
Method
To define an HTTP method (for example, GET or POST ) for a request, provide a value for the method property: a GET request whose result comes as a string:
Ktor provides extension functions for the HttpClient class for using basic HTTP methods: get , post , put , patch , delete , options , head . This is how you use them to send a GET request:
Headers
To add headers to the request, use the headers extension function.
To set the body of a request, assign a value to the body property in the HttpRequestBuilder class. You can assign a string or an OutgoingContent object to this property. For example, sending data with a text/plain text MIME type can be implemented as follows:
Response type
To obtain more information in the response, such as HTTP status, you can use the HttpResponse type as the request result:
For more information about the HttpResponse , refer to the Documentation.
You can also obtain the request results in the form of a byte array:
Multipart requests
To send a multipart request, pass a MultiPartFormDataContent object to the body property. Create this object by calling the MultiPartFormDataContent() constructor with the argument parts: List
. To create this list, use the FormBuilder builder class. It provides multiple variations of the append function for adding the data. There is also formData builder function, which accepts a lambda with the FormBuilder receiver.
An example of creating a POST request with Multipart data may look as follows:
Concurrency
The Ktor API is based on suspend functions, so Kotlin coroutines are used when working with asynchronous requests. Therefore, all requests must be executed in coroutines, which will suspend their execution while awaiting a response.
For concurrent execution of two or more requests, you can use coroutine builders: launch or async . For example, sending two concurrent requests using async might look as follows:
Close the HTTP client
After you finish working with the HTTP client, don’t forget to free up the resources that it uses: threads, connections, and CoroutineScope for coroutines. To do this, call up the close() function in HttpClient :
If you need to use HttpClient for a single request, call the extension function use() that will automatically calls close() after executing the code block:
Note that the close function prohibits the creation of new requests, but doesn’t terminate currently active ones. Resources will only be released after all client requests are completed
We’d like to thank the IceRock team for helping us write this article.
Источник
How to use Ktor client on Android
Walking to Kotlin multiplatform using Ktor Client
Ktor is an asynchronous open source framework for creating microservices and web applications. It was developed with Kotlin by Jetbrains. It’s easy to install and use, It’s extensible if you want to add a step to the execution pipeline. Its asynchronous property allows it to receive multiple requests thanks to coroutines and it is also multiplatform.
Ktor is multiplatform, yes multiplatform! It means that we can deploy Ktor applications anywhere, and not only as a server, but we can also consume microservices on Android, iOS, or JS with Ktor Client. Ktor Client allows you to make requests and handle responses, extend its functionality with features, such as authentication, JSON serialization, and so on.
We will learn how to configure, how to create client instances, and how to consume the REST API.
Let’s start by including the following dependencies in the build gradle.
The first dependency is the engine that handles network requests, we will use the android client for this case. The second dependency is used for JSON serialization and deserialization settings and is recommended for multiplatform projects. The third dependency is kotlinx.serialization, which is used for entity serialization. Finally, the fourth is for logging HTTP requests.
Now, we continue to include kotlinx.serialization plugin in the project gradle.
Now let’s configure the engine and create the client instance.
Depending on the engine (Android, Apache, OKHttp, etc), you could have different properties. We did the following in this configuration:
- First, we configure the JSON serializer / deserializer with kotlinx.serialization by adding various properties. We also define a timeout period.
- Second, we configure the logging to create HTTP request logs.
- Third, we configure an observer that will record all the states of the responses.
- Finally, we can set default values for each HTTP request. In this case, we define properties in the header, these will go in all requests.
Done! Ktor is now configured and the instance is ready to use. Keep calm, this is a one-time job. Let‘s use it!
We start to define the entity:
We continue configuring the UserApi:
We continue configuring the repository:
Finally, we will handle exceptions with an extension function:
Congrats! We have configured, created the client, and created requests to an API with Ktor. The advantages are that It is simple to implement, it is multiplatform, it uses coroutines internally, it doesn’t use annotations and It has a variety of configuration options, depending on the use case and requirements. One downside could be that it is a bit more verbose to set up and use than other ways.
I hope you find it useful, remember to share this article.
Источник