Ktor 3.0.1 Help

Proxy

Ktor HTTP client allows you to configure proxy settings in multiplatform projects. There are two supported types of proxies: HTTP and SOCKS.

Supported engines

The table below shows supported proxy types for specific engines:

Engine

HTTP proxy

SOCKS proxy

Apache

✖️

Java

✖️

Jetty

✖️

✖️

CIO

✖️

Android

OkHttp

JavaScript

✖️

✖️

Darwin

✖️

Curl

Add dependencies

To configure the proxy in the client, you don't need to add a specific dependency. The required dependencies are:

Configure proxy

To configure proxy settings, call the engine function inside a client configuration block and then use the proxy property. This property accepts the ProxyConfig instance that can be created using the ProxyBuilder factory.

val client = HttpClient() { engine { proxy = // Create proxy configuration } }

HTTP proxy

The example below shows how to configure HTTP proxy using ProxyBuilder:

val client = HttpClient() { engine { proxy = ProxyBuilder.http("http://sample-proxy-server:3128/") } }

On JVM, ProxyConfig is mapped to the Proxy class, so you can configure the proxy as follows:

val client = HttpClient() { engine { proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("sample-proxy-server", 3128)) } }

SOCKS proxy

The example below shows how to configure SOCKS proxy using ProxyBuilder:

val client = HttpClient() { engine { proxy = ProxyBuilder.socks(host = "sample-proxy-server", port = 1080) } }

As for the HTTP proxy, on JVM you can use Proxy to configure proxy settings:

val client = HttpClient() { engine { proxy = Proxy(Proxy.Type.SOCKS, InetSocketAddress("sample-proxy-server", 1080)) } }

Proxy authentication and authorization

Proxy authentication and authorization are engine-specific and should be handled manually. For example, to authenticate a Ktor client to an HTTP proxy server using basic authentication, append the Proxy-Authorization header to each request as follows:

val client = HttpClient() { defaultRequest { val credentials = Base64.getEncoder().encodeToString("jetbrains:foobar".toByteArray()) header(HttpHeaders.ProxyAuthorization, "Basic $credentials") } }

To authenticate a Ktor client to a SOCKS proxy on JVM, you can use the java.net.socks.username and java.net.socks.password system properties.

Last modified: 02 April 2024