使用Kotlin Ktor Client通过代理访问Cloudflare站点遇403错误的解决
使用Ktor HttpClient通过代理访问Cloudflare站点时的403错误修复
我尝试用代理访问受Cloudflare保护的站点,仅在使用代理时会触发Cloudflare的403 Forbidden错误,不使用代理则可正常访问。经测试这些代理本身无问题——用Python的requests模块及浏览器访问均未被拦截。
初始代码(触发403错误)
suspend fun scrape() { val client = HttpClient { followRedirects = true install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } engine { proxy = ProxyBuilder.http("http://ProxyIP:proxyPort") } defaultRequest { val credentials = Base64.getEncoder().encodeToString("ProxyUser:ProxyPassword".toByteArray()) header(HttpHeaders.ProxyAuthorization, "Basic $credentials") } } val response = client.get("http://example.com") val body = response.bodyAsText() println(body) println(response.status.hashCode()) }
修复后的代码(解决403问题)
suspend fun scrape() { val client = HttpClient(Apache) { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } engine { followRedirects = false customizeClient { setProxy(HttpHost("hostname", port)) val credentialsProvider = BasicCredentialsProvider() credentialsProvider.setCredentials( AuthScope("hostname", port), UsernamePasswordCredentials("username", "password") ) setDefaultCredentialsProvider(credentialsProvider) } } } val response = client.get("http://example.com") {} val body = response.bodyAsText() println(body) println(response.status.hashCode()) }
核心修复说明
- 切换使用Apache引擎:替代Ktor默认引擎,利用Apache HttpClient成熟的代理认证机制,避免手动构造认证头可能出现的格式或流程问题
- 禁用自动跟随重定向:防止重定向过程中请求特征变化被Cloudflare的反爬机制识别,同时确保代理认证信息在整个请求流程中正确传递
- 使用Apache原生认证管理:通过
BasicCredentialsProvider配置代理认证,而非手动添加ProxyAuthorization头,确保认证流程符合HTTP标准,减少被拦截的概率
内容的提问来源于stack exchange,提问作者Yuutokata
相关产品推荐
相关产品推荐

