我开始学习python。我正在尝试这本书的代码。
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
except Exception as e:
print(e)
try:
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print data
except Exception as e:
print(e)
mysock.close()
我尝试连接的网页无关紧要,我收到404错误。 我运行代码时得到以下内容。
HTTP/1.1 404 Not Found
Server: nginx
Date: Tue, 23 May 2017 17:54:54 GMT
Content-Type: text/html
Content-Length: 162
Connection: close
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
答案 0 :(得分:1)
WDFClasses.m
您正在尝试发送HTTP请求,但有多个问题。其中一些会导致问题,而其他服务器会被这个特定服务器忽略:
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
而不是\r\n
\n
。 HTTP / 1.1可以接受绝对值,但使用HTTP / 1.0。/code/romeo.txt
标头指定要访问的主机。在这种情况下,最后一项实际上是最重要的项目,但其他点也应该修复。因此,正确的请求看起来像这样
Host
有关详细信息,请参阅HTTP标准,即RFC 1945用于更简单的HTTP / 1.0和RFC 2616用于HTTP / 1.1,这更复杂但在实践中更常用。
答案 1 :(得分:0)
尝试更改此行mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
而不是mysock.connect(('www.py4inf.com', 80))
mysock.send('GET /code/romeo.txt HTTP/1.0\nHost:www.py4inf.com\n\n'.encode())
连接应如下所示:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET /code/romeo.txt HTTP/1.0\nHost:www.py4inf.com\n\n'.encode())
while True:
data = mysock.recv(512)
if (len(data) < 1):
break
print(data.decode(),end='')
mysock.close()
答案 2 :(得分:0)
我在这里做了改变,希望这会有所帮助:
Ps:也在第19行Print (data)
上,否则您将获得SyntaxError
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mysock.connect(('www.py4inf.com', 80))
#mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
mysock.send('GET /code/romeo.txt HTTP/1.0\nHost:www.py4inf.com\n\n'.encode())
except Exception as e:
print(e)
try:
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data)
except Exception as e:
print(e)
mysock.close()