ProxyForge Download

Proxy Setup in Kotlin for Web Scraping: OkHttp, Ktor, and Coroutines

Introduction

Kotlin is a statically typed language that runs on the JVM and offers seamless interoperability with Java. This makes it an excellent choice for developers looking to implement robust web scraping solutions using libraries like OkHttp, Ktor, and Kotlin coroutines. In this guide, we'll explore how to set up proxy configurations in Kotlin for HTTP requests, focusing specifically on authentication, concurrent processing, and efficient proxy rotation.

Setting Up Proxies with OkHttp

OkHttp is a popular HTTP client library for Java and Kotlin that supports proxy settings and authentication out of the box. To use a proxy with OkHttp, you need to configure both the proxy itself and any required authentication details.

Proxy Configuration with Authentication

Here's how to set up an authenticated HTTP proxy using OkHttp:

import okhttp3.*
import java.net.InetSocketAddress

// Define your proxy host, port, username, and password
val proxyHost = "proxy.example.com"
val proxyPort = 8080
val proxyUsername = "user"
val proxyPassword = "pass"

// Create a proxy object
val proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress(proxyHost, proxyPort))

// Set up the authenticator for the proxy
val authenticator = Authenticator { route, response ->
    if (response.request.header("Proxy-Authorization") != null) {
        return@Authenticator null
    }
    val credential = Credentials.basic(proxyUsername, proxyPassword)
    response.request.newBuilder()
        .header("Proxy-Authorization", credential)
        .build()
}

// Create an OkHttpClient with the proxy and authenticator
val client = OkHttpClient.Builder()
    .proxy(proxy)
    .authenticator(authenticator)
    .build()

// Make a request through the proxy
fun fetch(url: String) {
    val request = Request.Builder().url(url).build()
    client.newCall(request).execute().use { response ->
        if (!response.isSuccessful) throw IOException("Unexpected code $response")
        println(response.body!!.string())
    }
}

// Example usage
fetch("http://example.com")

Proxy Configuration with Ktor

Ktor is another powerful HTTP client for Kotlin that supports proxy settings through the ProxyConfig class. This section will guide you on setting up a proxy using Ktor.

Setting Up Proxies with Ktor

Here's how to configure a proxy in Ktor:

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*

// Define your proxy host and port
val proxyHost = "proxy.example.com"
val proxyPort = 8080

// Create a client with proxy configuration
val client = HttpClient(CIO) {
    engine {
        proxy = ProxyBuilder.http("$proxyHost:$proxyPort")
    }
}

// Make a request through the proxy
suspend fun fetch(url: String) {
    val response = client.get(url)
    println(response.bodyAsText())
}

// Example usage
fun main() {
    runBlocking {
        fetch("http://example.com")
    }
}

Proxy Rotation with Coroutines

For high-throughput web scraping, you might need to rotate proxies concurrently. This can be achieved using Kotlin coroutines along with a mutex-protected pool of proxies.

Concurrent Proxy Rotation with Mutex

Here's an example of how to implement proxy rotation using coroutines and mutexes:

import kotlinx.coroutines.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.system.measureTimeMillis

// Define your list of proxies in the format "host:port"
val proxyList = listOf("proxy1.example.com:8080", "proxy2.example.com:8080")

// Mutex for thread-safe access to the proxy pool
val mutex = ReentrantLock()
var currentProxyIndex = 0

// Function to get a proxy from the pool
fun getNextProxy(): String {
    return mutex.withLock {
        val proxy = proxyList[currentProxyIndex]
        currentProxyIndex = (currentProxyIndex + 1) % proxyList.size
        proxy
    }
}

// Coroutine-based proxy rotation
suspend fun fetchWithProxyRotation(url: String) {
    val client = OkHttpClient.Builder()
        .proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress(getNextProxy().split(":").first(), getNextProxy().split(":").last().toInt())))
        .build()

    val request = Request.Builder().url(url).build()
    client.newCall(request).execute().use { response ->
        if (!response.isSuccessful) throw IOException("Unexpected code $response")
        println(response.body!!.string())
    }
}

// Example usage
fun main() {
    runBlocking {
        repeat(10) {
            launch {
                fetchWithProxyRotation("http://example.com")
            }
        }
    }
}

Conclusion

Kotlin's coroutine model can outperform Python's asyncio for high-throughput web scraping due to its efficient handling of concurrent tasks and better integration with the JVM ecosystem. By leveraging libraries like OkHttp, Ktor, and Kotlin coroutines, developers can create robust, scalable web scraping solutions.

When dealing with professional or managed proxy services, Bright Data and SmartProxy are established providers offering reliable rotating proxies for production use. If you need a solution that auto-tests and rotates proxies locally on your machine without the need for ongoing subscriptions, ProxyForge offers a one-off purchase option at $29: https://proxyforge.dev/#download.

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →