V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
halfss
V2EX  ›  问与答

ruby uri invalid byte sequence in UTF-8 求解

  •  
  •   halfss · 2014-10-08 11:40:19 +08:00 · 3329 次点击
    这是一个创建于 3512 天前的主题,其中的信息可能已经有所发展或是发生改变。
    irb(main):010:0> URI("http://www.baidu.com/xEA\xE6").host
    ArgumentError: invalid byte sequence in UTF-8
    from /usr/lib64/fluent/ruby/lib/ruby/1.9.1/uri/common.rb:125:in `==='
    from /usr/lib64/fluent/ruby/lib/ruby/1.9.1/uri/common.rb:125:in `split'
    from /usr/lib64/fluent/ruby/lib/ruby/1.9.1/uri/common.rb:211:in `parse'
    from /usr/lib64/fluent/ruby/lib/ruby/1.9.1/uri/common.rb:747:in `parse'
    from /usr/lib64/fluent/ruby/lib/ruby/1.9.1/uri/common.rb:994:in `URI'
    from (irb):10
    from /usr/lib64/fluent/ruby/bin/irb:12:in `<main>'

    我需要获取这种情况下的host,遇到这个问题。网上搜了好久没找到合适的资料,哪位大大遇到过帮看看,在此感谢
    3 条回复    2014-10-08 14:27:12 +08:00
    halfelf
        1
    halfelf  
       2014-10-08 12:17:26 +08:00
    那个URI是从哪儿来的,\xEA\xE6应该不是完整的unicode字符表示。我现在手头没有1.9,2.1里肯定是自动转的。1.9应该差别不大
    halfss
        2
    halfss  
    OP
       2014-10-08 14:26:56 +08:00
    因为 "http://www.baidu.com/xEA\xE6" 包含了非法的 utf-8 字符

    str = "http://www.baidu.com/xEA\xE6"
    str.valid_encoding? # => false
    解决办法,先把 str 中得非法 utf-8 字符替换掉,比如替换成 ?

    for i in (0...str.size)
    unless str[i].valid_encoding?
    str[i] = "?"
    end
    end
    str.valid_encoding? # => true
    enjoy!
    halfss
        3
    halfss  
    OP
       2014-10-08 14:27:12 +08:00
    暂时就这样解决了,有更好的方法欢迎留言
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1046 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:20 · PVG 03:20 · LAX 12:20 · JFK 15:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.