使用Python3套接字打开OpenWeather API

是否有一种简单的方式只使用"套接字"来获得与使用urllib相同的输出:

uh = urllib.request.urlopen(url)
weather_decoded = uh.read().decode()

其中城市例如伦敦,api_key是您的密钥(您可以在终端运行:curl“URL”以查看输出的JSON文件)

weather_decoded现在保存当前有关城市的JSON文件

有没有一种更简单/更智能的方法使用"import socket"而不是导入urrlib

到目前为止,我所拥有的是:

import socket

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'

我要寻找的输出(来自URL的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}
点赞
用户3081018
用户3081018
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,这样您就不必处理连接保持和分块响应,尽管这个特定的服务器目前也没有使用这些功能。

2019-02-08 19:38:17