我正在尝试使用 python 发出 api 请求,为此我使用 http.client
我的逻辑在底部
我的 main.py 文件
import vatcompliance
client = vatcompliance.Client(api_key='TETEDKEY')
result = client.omp_feed(
{
'from_country': 'US',
'from_zip': '94025',
'from_state': 'CA',
'from_city': 'Menlo Park',
'from_street': '2825 Sand Hill Rd',
'to_country': 'US',
'to_zip': '94303',
'to_state': 'CA',
'to_city': 'Palo Alto',
'to_street': '5230 Newell Road',
'amount': 267.9,
'shipping': 0,
'getParams': {
'country': 'US',
'state': 'CA'
},
}
)
文件客户端.py
import http.client
import vatcompliance
from urllib.parse import urlencode
class Client():
def __init__(self, api_key):
self.params = None
self.method = None
self.url = None
self.api_key = api_key
def build_request(self):
params = urlencode(self.params)
headers = {"Content-type": "application/json", "Accept": "application/json"}
conn = http.client.HTTPSConnection(self.url)
conn.request("POST", "", params, headers)
response = conn.getresponse()
return response
def set_params(self, params, method, url):
self.params = params
self.method = method.upper()
self.url = url + '/' + vatcompliance.API_VERSION + '/' + self.api_key
if 'getParams' in self.params and self.method == 'POST':
self.url = self.url + '?' + urlencode(self.params['getParams'])
del self.params['getParams']
if self.method == 'GET':
self.url = self.url + '?' + urlencode(self.params)
def omp_feed(self, params):
self.set_params(params, 'POST', vatcompliance.OMP_API_URL)
return self.build_request()
我在尝试使用 HTTPSConnection 时遇到问题,我在控制台中收到此错误:
File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 887, in _get_hostport
port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '//omp.vatcompliance.co/api/v1/TETEDKEY?country=US&state=CA'
如何正确创建 http HTTPSConnection?我做错了什么?为什么他需要一个端口?