Hi,
Script below doesn't work suchas it works on Postman.
Response is 401.
Is it an API problem or script problem ?
import system
import features
from urllib import urlencode
clientID = "myclient_id"
clientSECRET = "myclient_secret"
url = "https://site.example/access_token"
body = {
"grant_type":"client_credentials"
}
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Authorization": "Basic xxxxxxxxx"
}
output = system.net.httpPost(
url=url,
contentType='application/x-www-form-urlencoded',
postData = urlencode(body),
username = clientID,
password = clientSECRET,
headerValues = headers
)
Thanks
Use system.net.httpClient
instead of system.net.httpPost
. It uses an entirely different (modern) engine that fixes many otherwise unfixable problems with the older functions.
It doesn't work too.
I get an error 400.
client = system.net.httpClient()
payload = {
"grant_type":"client_credentials",
"client_id":clientID,
"client_secret":clientSECRET
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic xxx'
}
res = client.post( url, payload, headers)
Can you post a snip of what your Postman window looks like? I've been bitten by this where Postman will automatically add some header that isn't visible and that will be the reason why it works there but not from an httpClient
HttpClient doesn't currently properly encode x-www-form-urlencoded
requests. Use urllib
to encode your POST data to a string, then httpClient()
should be able to send it.
It doesn't work with
from urllib import urlencode
res = client.post( url, urlencode(payload), headers)
What does 'doesn't work' mean?
Can you install Wireshark and look at the outgoing request and see if it matches what you expect?
you don't provide the scope = "/adict/v1" as in your other screenshot?
flavien
October 18, 2022, 1:50pm
10
same result with scope in headers.
Wireshark doesn't see any request HTTP POST even if I use Postman.
I use filter : http.request.method == “POST”
flavien
October 18, 2022, 2:54pm
11
It works !
My final script :
Don't use httpClient()
import system
import features
from urllib import urlencode
import httplib
clientID = "user"
clientSECRET = "pa$$w0rd"
baseUrl = "mysite.com"
url = "/a/b/access_token"
body = {
"scope":"/app/v1",
"grant_type":"client_credentials",
"client_id":clientID,
"client_secret":clientSECRET
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic xxx'
}
conn = httplib.HTTPSConnection(baseUrl)
conn.request("POST", url, urlencode(body), headers)
res = conn.getresponse()
data = res.read()
result = system.util.jsonDecode(data.decode("utf-8"))
return result
1 Like
flavien
October 21, 2022, 10:38am
12
With httplib it seems you can't get reponse body with PUT and POST requests.
Do you know an other way ?
pturmel
October 21, 2022, 12:30pm
13
Use httpClient with Paul's advice above.