When using the HTTPCollection module of the http.client module, while reading the contents of the site, an error 301 appears. The site itself works fine in the browser, when using the urlopen function everything works. I understand that the solution here is obvious: just use urlopen, but still I would like to know why this is so?
Here is the code:
from http.client import HTTPConnection privat = HTTPConnection('api.privatbank.ua', 80) privat.request('GET', '/p24api/pubinfo?json&exchange&coursid=5') result = privat.getresponse() print(result.read()) # выводит это: b'<html>\r\n<head><title>301 Moved Permanently</title></head>\r\n<body bgcolor="white">\r\n<center><h1>301 Moved Permanently</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n' Here is the working code:
import urllib.request, json with urllib.request.urlopen("http://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5") as url: data = json.loads(url.read().decode()) print(data) #выводит это: [{'ccy': 'USD', 'base_ccy': 'UAH', 'buy': '26.70000', 'sale': '26.95000'}, {'ccy': 'EUR', 'base_ccy': 'UAH', 'buy': '30.20000', 'sale': '30.70000'}, {'ccy': 'RUR', 'base_ccy': 'UAH', 'buy': '0.38700', 'sale': '0.41200'}, {'ccy': 'BTC', 'base_ccy': 'USD', 'buy': '3551.4864', 'sale': '3925.3270'}] I can’t understand why in the first code there is an error 301(b'<html>\r\n<head><title>301 Moved Permanently</title></head>\r\n<body bgcolor="white">\r\n<center><h1>301 Moved Permanently</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n') , and in the second everything works fine