Python:当您使用外部网络API时,如何摆脱超时错误?

时间:2018-11-07 07:43:55

标签: python python-3.x python-requests

当我使用邮递员工具时,一切工作正常,但是当我尝试使用Python http客户端/请求获取访问令牌时。两次都因错误而结束。

当我使用http.client

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

或者当我使用request时,会话内容

ConnectionError: HTTPSConnectionPool(host='identity.trimble.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000000088F49E8>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))

这是我的代码

import http.client, urllib.request, urllib.parse, urllib.error, base64
url = 'https://someurl'

client_id = 'some key' #Consumer Key
client_secret = 'secret' #Consumer Secret

Auth = base64.b64encode("{id}:{secrete}".format(**{'id' : client_id,
                                                   'secrete': client_secret}).encode('utf-8'))
header = {
    'authorization': 'Basic %s' % Auth.decode('utf-8'),
    'content-type' : 'application/x-www-form-urlencoded',
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
body = urllib.parse.urlencode({
    'grant_type' : 'password',
    'username' : 'usr@gmail.com',
    'password' : 'somepwd',
    'scope' : 'scope'
})
conn = http.client.HTTPSConnection('identity.trimble.com')

conn.request("POST", "/token", body=body, headers=header)
response = conn.getresponse()
print(response.code)
if response.code == 200:
    data = json.loads(response.read())
    print(data.get('access_token', None))
    #access_token['ttl'] = datetime.now() + timedelta(seconds=data.get('expires_in', 10))
conn.close()

我在公司VPN中有什么作用吗?我想知道,因为它与Postman工具配合正常。

谢谢

0 个答案:

没有答案