使用luasocket HTTP GET中文字符

时间:2012-11-24 01:51:27

标签: sockets unicode lua cjk luasocket

我使用luasocket来获取一个包含中文字符“开奖结果”(页面本身编码为charset =“gb2312”)的网页,如下所示:

require "socket"
host = '61.129.89.226'
fileformat = '/fcopen/cp_kjgg_dfw.jsp?lottery_type=ssq&lottery_issue=%s'
function getlottery(num)
  c = assert(socket.connect(host, 80))
  c:send('GET ' .. string.format(fileformat, num)  .. " HTTP/1.0\r\n\r\n")
  content = c:receive('*l')
  while content do
    if content and content:find('开奖结果') then -- failed
      print(content)
    end
    content = c:receive('*l')
  end
  c:close()
end

--http://61.129.89.226/fcopen/cp_kjgg_dfw.jsp?lottery_type=ssq&lottery_issue=2012138
getlottery('2012138')

不幸的是,它无法匹配预期的字符:

content:find('开奖结果') -- failed

我知道Lua能够找到unicode字符:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> if string.find("This is 开奖结果", "开奖结果") then print("found!") end
found!

然后我想这可能是由于luasocket如何从网上检索数据引起的。任何人都可以对此有所了解吗?

感谢。

1 个答案:

答案 0 :(得分:4)

如果页面是用GB2312编码的,而你的脚本(文件本身)是用utf-8编码的,那么匹配就无法工作。因为.find()会查找utf-8代码点,它只会滑过你正在寻找的字符,因为它们的编码方式不一样......

          开    奖      结     果
GB      bfaa   bdb1   bde1   b9fb
UTF-16  5f00   5956   7ed3   679c
UTF-8   e5bc80 e5a596 e7bb93 e69e9c