我刚刚创建了一个简单的网站testingtest.comyr.com(.php文件只包含一个回声" Hello,world!";)从网站www.000webhost.com托管,我想要的只是打印上写的内容(" Hello,world!" text)。我使用的代码(请注意我只能使用" socket"库到我的项目):
sok1 = require("socket")
Host = "testingtest.comyr.com"
Link = "/"
sok2 = sok1.connect(Host, 80)
sok2:send("GET "..Link.." HTTP/1.0\r\n\r\n")
receive = sok2:receive('*a')
print(receive)
但是这给了我:
HTTP/1.1 302 Found
Date: Wed, 01 Oct 2014 17:03:01 GMT
Server: Apache
Location: http://error404.000webhost.com/?
Content-Length: 216
Connection: close
Connection-type: text/hmtl; charset=iso-8859-1
<!DOCUMENT HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
The document has moved here.
</body></html>
答案 0 :(得分:3)
您正在使用302
标题返回Location
状态,该标题表示重定向,以及您要重定向到的新网址。由于您使用的是原始套接字模块,因此它不会处理重定向;您需要使用socket.http
模块为您处理,或者编写一些逻辑来解析响应以查找Location
标头,如果您获得任何3xx代码,然后使用新URL重复请求。
鉴于重定向的网址为error404.000webhost.com
(404表示&#34;找不到网页&#34;),您也可能在部署放在一起的PHP页面时犯了一些错误。< / p>
这样的事情可能能够处理重定向(如果你只能根据你的评论使用&#34; socket&#34;库):
sok1 = require("socket")
Host = "testingtest.comyr.com"
Link = "/"
local hosts = {}
while true do
sok2 = sok1.connect(Host, 80)
sok2:send("GET "..Link.." HTTP/1.1\r\nHost: "..Host.."\r\n\r\n")
receive = sok2:receive('*a')
-- check if this is a redirect
if receive:find("^HTTP/1%.%d 3%d%d") then
local host, link = receive:match("Location: http://([^/\r\n]+)(/?[^\r\n]*)")
if host and link and not hosts[host] then
Host, Link = host, #link > 0 and link or "/"
hosts[host] = true -- keep track of redirects to avoid loops
print("redirecting to", host..link)
end
else
break -- done
end
end
print(#receive)
逻辑检查循环,但它只处理重定向到http:
URL(您需要检查https并将端口80更改为443)。我还添加了Host
标头,因为它可能不适用于在同一IP地址上托管多个域的某些ISP提供商。