Python3 OpenWeather API 使用套接字

Python3 OpenWeather API using sockets

有没有一种简单的方法可以只导入相同的输出 "sockets" 因为这 3 行代码使用 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 文件,其中包含有关城市的当前信息

有没有 easy/smart 方法使用 "import socket" 而不是导入 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))

但这只是 returns 我使用了一个错误的请求,我显然这样做了,但到目前为止,我发现的大多数请求看起来都和我的一样。

我得到的输出:

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}
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 后的路径和主机 header 的域。这意味着请求应如下所示:

GET /data/2.5/weather?q=London,... HTTP/1.1
Host: api.openweathermap.org

除此之外,行尾应该是 \r\n 而不是 \n 尽管这个特定的服务器不关心。而且,你最好使用 HTTP/1.0 而不是 HTTP/1.1 这样你就不必处理连接 keep-alive 和分块响应,尽管这个特定的服务器目前也不使用它。