system.net.httpClient with CookieManager

Just wanted to post some code I was working on today. Couldn’t really find much on the forum to help with how to deal with the java cookie policy if the HTTP client required it for the get calls, but fought my way through it with some help on other sites. Hopefully, this helps someone else in the future.

This is my first time trying this so if someone sees something out of wack or way to make it better I would appreciate any feedback.

# This will set the login URL
loginURL = 'API login url'
badge = 'some username'
pin = 'some password'

import urllib
loginPayload = urllib.urlencode({"badge":badge,"pin":pin})

# header required for the http post call - this was grabbed from the API Manual
header = {'Content-Type': "application/x-www-form-urlencoded"}

# make the HTTP client - Bypass certification 
http = system.net.httpClient(bypass_cert_validation=True)
# make the post call to get the returned cookie needed for the header of the Get scripts below.
response = http.post(url=loginURL, data=loginPayload,headers=header)

# Get the cookie manager from Java - This is needed to get the user credential cookie from above to use for all calls
from java.net import CookiePolicy
if response.good:
	cookieJar = http.getCookieManager()
	#Grabs the first cookie returned from cookieManager in the list to be returned and used in http.get calls.
	userToken = cookieJar.getCookieStore().getCookies()[0]
	#print userToken
else:
	print 'Auth Failed - ' + str(response.json)

# set the product url - this was grabbed from the API manual	
productsURL = 'some url to the products section'

# This header is needed to pass the authentication cookie to the get call
productHeader = {'Cookie': userToken, 'Content-Type': 'application/json'}
productResponse = http.get(url=productsURL, headers=productHeader)

# grab all of product codes from API
i=0
if productResponse.good:
	while i < len(productResponse.json):
		products = productResponse.json[i]['product']
		i= i+1
		print products
else:
	print 'Product Return Failed - ' + str(productResponse.json)
4 Likes

Thanks for posting this. It helped me out with the project I'm working on