All functions used to make an HTTP request (
post, etc.) allow you to receive a response as an HttpResponse object.
HttpResponse exposes the API required to get a response body in various ways (raw bytes, JSON objects, etc.) and obtain response parameters, such as a status code, content type, headers, and so on. For example, you can receive
HttpResponse for a
GET request without parameters as follows:
Receive response parameters
The HttpResponse class allows you to get various response parameters, such as a status code, headers, HTTP version, and so on.
To get the status code of a response, use the HttpResponse.status property, for example:
The HttpResponse.headers property allows you to get a Headers map containing all response headers.
HttpResponse also exposes a bunch of specific functions for receiving specific header values, for example:
charsetfor a charset from the
Receive response body
To receive a raw body of a response, call the
body function and pass the required type as a parameter. The code snippet below shows how to receive a raw body as String:
Similarly, you can get a body as ByteArray:
A runnable example below shows how to get a response as a byte array and save it to a file:
With the ContentNegotiation plugin installed, you can deserialize JSON data into a data class when receiving responses, for example:
To learn more, see Receive and send data.
Note: there are ContentNegotiation plugins for both client and server, make sure to use proper one (client in this case).
When you call the
HttpResponse.body function to get a body, Ktor processes a response in memory and returns a full response body. If you need to get chunks of a response sequentially instead of waiting for the entire response, use
HttpStatement with scoped execute block. A runnable example below shows how to receive a response content in chunks (byte packets) and save them in a file: