无法通过传递REST API的参数来形成URL

时间:2018-10-26 19:02:28

标签: python

我正在尝试调用REST API,并将所需的值作为参数传递。

首先,我尝试直接传递值并获得了预期的URL值。 我模拟了所有值以隐藏原始凭据,但原始请求的格式相同。

代码:

GATE_API ='https://gateway-stage-core.milton.com/auth/oauth2/token'

payload = {'id': '8888yxy','secret':'vUz65MZ','type' : 'client','consumer_id' : '673d5881'}
print payload

r = requests.post(GATE_API, params = payload, verify=False)
print r.url

输出:

{'secret': 'vUz65MZ', 'type': 'client', 'id': '8888yxy', 'consumer_id': '673d5881'}
https://gateway-stage-core.milton.com/auth/oauth2/token?client_secret=vUz65MZ&type=client&id=8888yxy&consumer_id=673d5881

但是在原始代码中,我必须将这些凭据作为参数传递。输出URL带有很多垃圾值,无法匹配上面的值。

代码:

GATE_API ='https://gateway-stage-core.milton.com/auth/oauth2/token'
ID = '8888yxy'
SECRET = 'vUz65MZ'
TYPE = 'client'
CONSUMER_ID= '673d5881'

payload = '{' + '"' + 'id' + '"' + ':' + '"' + ID + '"' + "," + '"' + 'secret' + '"' + ':' + '"' + SECRET + '"' + "," +'"' + 'type' + '"' + ':' + '"' + TYPE + '"' + "," + '"' + 'consumer_id' + '"' + ':' + '"' + CONSUMER_ID + '"' + '}`' 
print payload

r = requests.post(GATE_API, params = payload, verify=False)
print r.url

输出:

{"id":"8888yxy","secret":"vUz65MZ","type":"client","consumer_id":"673d5881"}
https://gateway-stage-core.milton.com/auth/oauth2/token?%7B%22id%22:%228888yxy%22,%22secret%22:%22vUz65MZ%22,%22type%22:%22client%22,%22consumer_id%22:%22673d5881%22%7D

1 个答案:

答案 0 :(得分:1)

在第二个示例中,您将有效负载作为字符串而不是字典传递。 “垃圾值”是有效负载字符串中非字母数字字符的转义字符串。