使用luasocket的HTTP GET中文字符

我使用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版版权所有(C) 1994-2008 Lua.org,PUC-Rio
> if string.find("This is 开奖结果", "开奖结果") then print("found!") end
found!

那么我猜这可能是由于luasocket如何从网络检索数据引起的。有人可以对此进行解释吗?

谢谢。

点赞
用户1136195
用户1136195

如果页面采用了 GB2312 编码,而你的脚本文件本身采用 utf-8 编码,那么匹配是不会成功的。因为 .find() 方法会寻找 utf-8 码位,而它只会忽略你要查找的字符,因为它们的编码方式不同...

          开    奖      结     果
GB      bfaa   bdb1   bde1   b9fb
UTF-16  5f00   5956   7ed3   679c
UTF-8   e5bc80 e5a596 e7bb93 e69e9c
2012-11-24 04:46:49