Script urlEncode example?

My head is slightly fried today. Can anyone show me how to encode the URL:

client = system.net.httpClient()
machine = 3
sku = '123 45'
response = client.get("http://10.11.12.13/proxy/recipes.php?machine=%s&sku=%s" % (str(machine), str(sku)))

The space in sku is causing the problem.

Many thanks.

did you try replacing the space with %20?

Supposedly you can do this too:

import urllib
params = {
	'machine': 3,
	'sku': '123 45'
}
baseUrl = 'http://10.11.12.13/proxy/recipes.php'
urlEncodedParams = urllib.urlencode(params)

url = "%s?%s" % (baseUrl, urlEncodedParams)

prints out http://10.11.12.13/proxy/recipes.php?machine=3&sku=123+45

No, while that might work, I want to do it properly! :wink:
The sku value is passed into the script so I would have to urlEncode that before merging it with the rest of the URL.


Oh, I see you've added more. I'll try that now.

I strongly recommend not using urllib. Instead use Java's standard URLEncoder class. Consider using the method that takes a Charset object. See the list from StandardCharsets.

{ I recommend not using any jython libraries when java or the jars included in Ignition have an alternative. Better performance, fewer bugs, and no issues with python2's lack of encoding awareness. That is my definition of "properly". }

2 Likes

You don't need to do any manual encoding. system.net.httpClient will do it for you.

client = system.net.httpClient()
params = dict(machine=3, sku='123 45')
response = client.get("http://10.11.12.13/proxy/recipes.php", params=params)

Proof:

from pprint import pprint

client = system.net.httpClient()
params = dict(machine=3, sku='123 45')
response = client.get("http://httpbin.org/get", params=params)

pprint(response.json)
>>> 
{'args': {'machine': u'3', 'sku': u'123 45'},
 'headers': {'Content-Length': u'0',
             'Host': u'httpbin.org',
             'Http2-Settings': u'AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA',
             'Upgrade': u'h2c',
             'User-Agent': u'Ignition',
             'X-Amzn-Trace-Id': u'Root=1-63ee5f84-75acab695cd7841d1434ed14'},
 'origin': u'104.220.10.151',
 'url': u'http://httpbin.org/get?machine=3&sku=123+45'}
8 Likes