Zum Inhalt springen
GProxy
Registrierung
Гайды 2 Min. Lesezeit 21 Aufrufe

Verwenden von Proxies in Kotlin

Proxy-Einrichtung in Kotlin: OkHttp, Ktor, Java Proxy API, SOCKS5 und Authentifizierung für Android- und JVM-Anwendungen.

Verwenden von Proxies in Kotlin

Proxys in Kotlin verwenden

Proxys in Kotlin

Kotlin läuft auf der JVM und hat vollen Zugriff auf die Java-API für die Arbeit mit Proxys. Zusätzlich bieten beliebte Kotlin-Bibliotheken (OkHttp, Ktor) eigene komfortable APIs zur Konfiguration von Proxys.

OkHttp (Empfohlen)

OkHttp ist der beliebteste HTTP-Client für Kotlin/Android.

HTTP-Proxy

import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.InetSocketAddress
import java.net.Proxy

val proxy = Proxy(
    Proxy.Type.HTTP,
    InetSocketAddress("proxy_ip", 8080)
)

val client = OkHttpClient.Builder()
    .proxy(proxy)
    .build()

val request = Request.Builder()
    .url("https://httpbin.org/ip")
    .build()

client.newCall(request).execute().use { response ->
    println(response.body?.string())
}

SOCKS5-Proxy

val proxy = Proxy(
    Proxy.Type.SOCKS,
    InetSocketAddress("proxy_ip", 1080)
)

val client = OkHttpClient.Builder()
    .proxy(proxy)
    .build()

Authentifizierung

import okhttp3.Authenticator
import okhttp3.Credentials
import okhttp3.Route

val proxyAuthenticator = Authenticator { _: Route?, response: okhttp3.Response ->
    val credential = Credentials.basic("username", "password")
    response.request.newBuilder()
        .header("Proxy-Authorization", credential)
        .build()
}

val client = OkHttpClient.Builder()
    .proxy(proxy)
    .proxyAuthenticator(proxyAuthenticator)
    .build()

Ktor Client

Ktor ist ein asynchrones Framework von JetBrains, nativ für Kotlin.

HTTP-Proxy

import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import java.net.InetSocketAddress
import java.net.Proxy

val client = HttpClient(OkHttp) {
    engine {
        proxy = Proxy(
            Proxy.Type.HTTP,
            InetSocketAddress("proxy_ip", 8080)
        )
    }
}

suspend fun main() {
    val response: HttpResponse = client.get("https://httpbin.org/ip")
    println(response.bodyAsText())
    client.close()
}

Mit CIO Engine

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

val client = HttpClient(CIO) {
    engine {
        proxy = io.ktor.client.engine.ProxyBuilder.http("http://proxy_ip:8080")
    }
}

SOCKS über Ktor

val client = HttpClient(OkHttp) {
    engine {
        proxy = Proxy(
            Proxy.Type.SOCKS,
            InetSocketAddress("proxy_ip", 1080)
        )
    }
}

Java Proxy API

Die Standard-Java-API funktioniert in Kotlin:

import java.net.HttpURLConnection
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.URL

val proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("proxy_ip", 8080))
val url = URL("https://httpbin.org/ip")
val connection = url.openConnection(proxy) as HttpURLConnection

// Аутентификация
val encoded = java.util.Base64.getEncoder()
    .encodeToString("user:pass".toByteArray())
connection.setRequestProperty("Proxy-Authorization", "Basic $encoded")

connection.inputStream.bufferedReader().use { reader ->
    println(reader.readText())
}

Proxy-Rotation

import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.InetSocketAddress
import java.net.Proxy

data class ProxyConfig(val host: String, val port: Int, val user: String, val pass: String)

val proxies = listOf(
    ProxyConfig("proxy1", 8080, "user", "pass"),
    ProxyConfig("proxy2", 8080, "user", "pass"),
    ProxyConfig("proxy3", 8080, "user", "pass"),
)

fun getClient(proxyConfig: ProxyConfig): OkHttpClient {
    val proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress(proxyConfig.host, proxyConfig.port))
    return OkHttpClient.Builder()
        .proxy(proxy)
        .proxyAuthenticator { _, response ->
            val credential = okhttp3.Credentials.basic(proxyConfig.user, proxyConfig.pass)
            response.request.newBuilder()
                .header("Proxy-Authorization", credential)
                .build()
        }
        .build()
}

fun fetchWithRotation(url: String): String? {
    val proxy = proxies.random()
    val client = getClient(proxy)
    val request = Request.Builder().url(url).build()
    return try {
        client.newCall(request).execute().use { it.body?.string() }
    } catch (e: Exception) {
        println("Failed with ${proxy.host}: ${e.message}")
        null
    }
}

Android-spezifische Überlegungen

Android System-Proxys

Unter Android können Sie System-Proxys verwenden:

val proxyHost = System.getProperty("http.proxyHost")
val proxyPort = System.getProperty("http.proxyPort")?.toIntOrNull()

NetworkSecurityConfig

Um mit Proxys unter Android 7+ zu arbeiten, müssen Sie network_security_config.xml konfigurieren, um Klartext-Traffic zu erlauben (wenn der Proxy HTTP ist).

Retrofit + Proxy

val proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("proxy_ip", 8080))
val okHttpClient = OkHttpClient.Builder().proxy(proxy).build()

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

Timeouts und Einstellungen

import java.util.concurrent.TimeUnit

val client = OkHttpClient.Builder()
    .proxy(proxy)
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .retryOnConnectionFailure(true)
    .build()

Fazit

Kotlin bietet mehrere Möglichkeiten zur Arbeit mit Proxys: OkHttp für Einfachheit und Leistung, Ktor für einen asynchronen, Coroutine-basierten Ansatz und die Standard-Java-API für Kompatibilität. Für die Android-Entwicklung ist OkHttp + Retrofit der Industriestandard. Alle Optionen unterstützen HTTP- und SOCKS5-Proxys mit Authentifizierung.

Aktualisiert: 06.03.2026
Zurück zur Kategorie

Testen Sie unsere Proxys

20.000+ Proxys in über 100 Ländern weltweit

support_agent
GProxy Support
Usually replies within minutes
Hi there!
Send us a message and we'll reply as soon as possible.