如何在Kotlin中将win1251编码转换为UTF8?

Jak*_*oid 2 http utf-8 cp1251 kotlin

我正在向页面发出HTTP请求。此页面有西里尔字符。如何将CP1251中的答案转换为UTF8?

这是我的代码。

package bash

import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.result.Result

fun main(args: Array<String>) {
    val bashImHost = "http://bash.im/"
    bashImHost.httpGet().responseString { request, response, result ->
        when (result) {
            is Result.Failure -> {
                println("Some kind of error!")
            }
            is Result.Success -> {
                val htmlBody = result.value
                val parsePattern = "<div class=\"text\">(.+)</div>"
                val parseRegex = Regex(parsePattern)
                val results = parseRegex.findAll(htmlBody)
                results.iterator().forEach { resultItem -> println(resultItem.groups[1]?.value) }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Fuel HTTP库。

hot*_*key 5

使用responseString接受的重载Charset使其使用Charset.forName("Windows-1251")以下命令解码响应:

bashImHost.httpGet().responseString(Charset.forName("Windows-1251")) {
    request, response, result ->

    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

似乎您无法String使用正确的编码UTF-8 将响应转换为Windows-1251后,无法更改对Windows-1251的响应的编码,请参阅此问答