我正在尝试使用urllib3连接到网页。代码如下所示。
import urllib3
http=urllib3.PoolManager()
fields={'username':'abc','password':'xyz'}
r=http.request('GET',url,fields)如果我们假设url是某个需要使用用户名和密码进行身份验证的网页,那么我是否使用了正确的代码进行身份验证?
我已经用urllib2很好地做到了这一点,但我不能用urllib3做同样的事情。
非常感谢
发布于 2012-07-09 10:56:44
假设您正在尝试执行Basic Authentication,那么您需要将用户名和密码编码到Authorization标头中。以下是使用urllib3.make_headers帮助器完成此操作的一种方法:
import urllib3
http = urllib3.PoolManager()
url = '...'
headers = urllib3.make_headers(basic_auth='abc:xyz')
r = http.request('GET', url, headers=headers)发布于 2020-08-18 02:04:31
下面是一个使用请求库(使用Python3.6的ubuntu)验证API的工作示例。希望它能帮上忙!
import json
import requests
from requests.auth import HTTPBasicAuth
def __init__(self):
header = {"Content-Type": "application/json"}
access_url = "https://your.login.url/context_path"
data = {
"key_to_send":"value_to_send"
}
def get_token(self):
self.data = json.dumps(self.data)
encoded_data = json.dumps(self.data).encode('utf-8')
self.response = requests.post(self.access_url, auth=HTTPBasicAuth(self.username, self.password), headers=self.header, data=self.data)
# Show me what you found
print(self.response.text)https://stackoverflow.com/questions/11335825
复制相似问题