【问题标题】:How convert win1251 encoding to UTF8 inside Kotlin?如何在 Kotlin 中将 win1251 编码转换为 UTF8?
【发布时间】:2017-11-15 16:07:38
【问题描述】:

我正在向页面发出 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) }
            }
        }
    }
}

我正在使用 Fuel HTTP 库。

【问题讨论】:

    标签: http utf-8 kotlin cp1251


    【解决方案1】:

    使用接受CharsetresponseString 重载使其使用Charset.forName("Windows-1251") 解码响应:

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

    使用错误的 UTF-8 编码将响应转换为String 后,您似乎无法将响应的编码更改为 Windows-1251,请参阅this Q&A

    【讨论】:

    • 如果 responseJson 怎么样?
    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2020-09-30
    相关资源
    最近更新 更多