This post will discuss how to send HTTP GET and POST request in Kotlin.

1. Using URLConnection

We can send HTTP request in Kotlin using the java.net.URLConnection class. The idea is to get an URLConnection object by invoking the openConnection() function on a URL. Then get an input stream by calling getInputStream() and create a BufferedReader on the input stream to read from it.

Following is a simple example demonstrating HTTP GET request.

Download

Output:

 
Alternatively, to send an HTTP POST request, set URLConnection.setDoOutput() function to true and also write the POST parameters to the output stream of the connection. Here’s what the code would look like:

Download Code

Output:


{"args":{},"data":"","files":{},"form":{"foo1":"bar1","foo2":"bar2"},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-61c9d226-3a1f8340360c303e1da404e9","content-length":"19","content-type":"application/x-www-form-urlencoded","user-agent":"Java/13.0.1","accept":"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"},"json":{"foo1":"bar1","foo2":"bar2"},"url":"https://postman-echo.com/post"}

2. Using HttpUrlConnection

The java.net.HttpURLConnection class is the subclass of java.net.URLConnection, which offers several HTTP-specific features. To get a HttpURLConnection object, we can cast the URLConnection instance to HttpURLConnection. To send an HTTP POST request, we can pass "POST" string literal to the HttpURLConnection#setRequestMethod() function. This is preferable over setDoOutput() function of URLConnection class.

This is demonstrated below:

Download Code

Output:


{"args":{},"data":"","files":{},"form":{"foo1":"bar1","foo2":"bar2"},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-61c9d1dd-0bbed6304b2ee8fc17628da2","content-length":"19","content-type":"application/x-www-form-urlencoded","cache-control":"no-cache","pragma":"no-cache","user-agent":"Java/13.0.1","accept":"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"},"json":{"foo1":"bar1","foo2":"bar2"},"url":"https://postman-echo.com/post"}

 
The following code example demonstrates HTTP GET request using java.net.HttpUrlConnection.

Download

Output:

That’s all about sending HTTP GET and POST request in Kotlin.