Swift编码url到windowsCP1251添加百分比编码

时间:2017-03-29 17:32:06

标签: swift string encode

我有服务器要求在URL请求中使用windowsCP1251编码。 Objective-C上的遗留代码使用了不推荐使用的CFURLCreateStringByAddingPercentEscapes。

我可以用

mySting.addingPercentEscapes(using: String.Encoding.windowsCP1251)

但不推荐使用。如果我使用

str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

它给我错误的结果,因为此方法使用默认的UTF8编码。

例如我有这段代码

let mySting = "Задача"

//use deprecated method but return correct result
let correctResult = mySting.addingPercentEscapes(using: String.Encoding.windowsCP1251)
//returns "%C7%E0%E4%E0%F7%E0"   , that's correct

//uses recommended method but returns incorrect result
let incorrectResult = mySting.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
//returns "%D0%97%D0%B0%D0%B4%D0%B0%D1%87%D0%B0", that's incorrect

0 个答案:

没有答案