我有一个python函数,该函数接受参数并使用请求和基本授权将其发布到api端点。但是,在python中,我收到401错误(身份验证失败)。下面是我的代码:
request_body = '{"account": "%s"' % token
request_body += ', "expiry": "%s"'% expiry_mmyy
request_body += ', "name": "%s"' % name
request_body += ', "merchid": "%s"' % auth_merchant_id
request_body += ', "amount": "%s"' % amount
request_body += ', "tokenize": "y" '
request_body += ', "orderId": "%s"' % reference_number
request_body += ', "capture": "y"}'
json_string = json.dumps(request_body)
#commented this line out and it started working
#json_string = json_string[1:-1]
logger.info('JSON Request: %s' % json_string)
logger.info('Username: %s' % AUTH_USER)
logger.info('Password: %s' % AUTH_PASSWORD)
http_headers = {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": str(len(json_string)),
"Authorization": "Basic"
}
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
#response = requests.post(url=CC_URL, headers=http_headers, data=json_string, auth=("%s" % AUTH_USER, "%s" % AUTH_PASSWORD))
#response = requests.post(url=CC_URL, headers=http_headers, data=json_string, auth=('testing','testing123'))
#response = requests.post(CC_URL, verify=False, headers=http_headers, data={json_string}, auth=HTTPBasicAuth("%s" % AUTH_USER,"%s" % AUTH_PASSWORD))
response = requests.post(url=CC_URL, headers=http_headers, data=json_string, auth=HTTPBasicAuth('testing', 'testing123'))
if response.status_code == 200:
logger.info('POST Success (HTTP code 200)')
#response_string = response.json
response_string = response.text
logger.info('JSON Response: %s' % response_string)
logger.info(response_string['resptext'])
logger.info(response_string['authcode'])
else:
logger.info("Error Code %s" % response.status_code)
我不确定基本身份验证是否正常。任何帮助表示赞赏。
可能是TLS1.2问题;我不确定如何将上下文传递给requests.post?
安装的python版本是2.7,ssl版本是1.0.2k。
谢谢
编辑: 我尝试使用urllib2.urlopen对其进行测试,但仍然出现相同的错误。我联系了其他最终用户,他们说,他们的日志显示缺少http标头。而且,他看不到目标URL。
答案 0 :(得分:1)
您不必通过“ Authorization”:“ Basic”部分作为标题。只是request.post()上的auth = HTTPBasicAuth('testing','testing123')
答案 1 :(得分:0)
是这样的: json_string = json_string [1:-1]
我评论了这一行,它开始工作