是否有一种简单的方法来获得仅导入“套接字”的相同输出 如使用urllib的以下三行代码:
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid={}&units=metric'.format(city, api_key)
uh = urllib.request.urlopen(url)
weather_decoded = uh.read().decode()
例如城市在伦敦,而api_key是您的密钥(您可以在终端中运行:curl“ the url”,这样您就可以看到输出的json文件
weather_decoded现在保存带有有关该城市的当前信息的json文件
是否有使用“导入套接字”而不是导入urrlib的简单/智能方法来完成相同的事情
到目前为止,我是这样的:
导入套接字
server = 'api.openweathermap.org'
url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1'
port = 80
request = "GET / HTTP/1.1\nHost: " + url + "\n\n"
request_bytes = str.encode(request)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((server, port))
s.sendall(request_bytes)
data = s.recv(4096)
print(repr(data))
但这只是返回我使用了一个错误的请求,这显然是我做的,但是到目前为止,我发现的大多数请求看起来像我的。
我得到的输出:
b'HTTP/1.1 400 Bad Request\r\nServer: openresty\r\nDate: Fri, 08 Feb 2019 18:48:58 GMT\r\nContent-Type: text/html\r\nContent-Length: 166\r\nConnection: close\r\n\r\n<html>\r\n<head><title>400 Bad Request</title></head>\r\n<body bgcolor="white">\r\n<center><h1>400 Bad Request</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'
我正在寻找的输出(来自网址的json文件):
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"stations","main":{"temp":282.45,"pressure":993,"humidity":87,"temp_min":281.15,"temp_max":283.15},"visibility":10000,"wind":{"speed":5.7,"deg":230},"clouds":{"all":20},"dt":1549650000,"sys":{"type":1,"id":1414,"message":0.0039,"country":"GB","sunrise":1549610791,"sunset":1549645418},"id":2643743,"name":"London","cod":200}
答案 0 :(得分:1)
url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1'
port = 80
request = "GET / HTTP/1.1\nHost: " + url + "\n\n"
HTTP请求应在GET之后包含路径,并在Host标头中包含域。这意味着请求应如下所示:
GET /data/2.5/weather?q=London,... HTTP/1.1
Host: api.openweathermap.org
除了该行服务器,该行服务器的末尾应该为\r\n
而不是\n
。而且,最好使用HTTP/1.0
而不是HTTP/1.1
,这样就不必处理连接保持活动和分块的响应,尽管该特定服务器当前也不使用它。