Transition from requests to system.net.httpClient

Hello All - I would like to transition a script that we have running from using the requests module to system.net.httpClient. Not that there is an issue with the current method, but we transitioned to a new server and instead of getting requests set up on it, I would rather use the method that is available.

Here is the current script:

accessTokenResponse = requests.post(tokenUrl, data=data, verify=False, allow_redirects=False, auth=(self.clientId, self.clientSecret))

I am trying to use system.net.httpClient() along with client.post() to retrieve a bearer access token but am struggling on where to put the parameters for the request. Some of the methods I have tried are shown below but I continue to receive 400 error. Any other suggestions to try would be appreciated!

data = {'grant_type': 'client_credentials'}
header = {'clientId' : clientID, 'clientSecret' : clientSecret}
response = client.post(url=tokenUrl, data=data, headers=header)

client = system.net.httpClient()
response = client.post(url=tokenUrl, data=data, username=clientID, password=clientSecret)

I don't have an answer for you, but I took the liberty of editing your post so the code is correctly formatted. In the future you can do this yourself by surrounding your code with triple-backticks. Makes everything much easier to read, which will get you answers faster.

1 Like