简体   繁体   中英

Python requests module url encode

I'm trying to send json as a parameter thru a get method for an api, I found that the url to which it is hitting is little bit different from the original url. Some ":%20" text is inserted in between the url. Not sure why this difference is coming, Can someone help

Original URL: http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest=%7B%22rajNames%22%3A%5B%22WAR%22%5D%7D

My URL : http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest=&%7B%22rajNames%22:%20%22WAR%22%7D

Python code:

headers = {'Accept': 'application/json','Authorization': 'Bearer '+access_token}
json = {'rajNames':'WAR'}
url = 'http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest='
r = requests.get(url, params=json.dumps(json),headers=headers)
print _r.url

The spaces are not the problem; your method of generating the query string is , as is your actual JSON payload.

Note that your original URL has a different JSON structure:

>>> from urllib import unquote
>>> unquote('%7B%22rajNames%22%3A%5B%22WAR%22%5D%7D')
'{"rajNames":["WAR"]}'

The rajNames parameter is a list, not a single string.

Next, requests sees all data in params as a new parameter, so it used & to delimit from the previous parameter. Use a dictionary and leave the ?jsonRequest= part to requests to generate:

headers = {'Accept': 'application/json', 'Authorization': 'Bearer '+access_token}
json_data = {'rajNames': ['WAR']}
params = {'jsonRequest': json.dumps(json_data)}
url = 'http://258.198.39.215:8280/areas/0.1/get/raj/name'
r = requests.get(url, params=params, headers=headers)
print _r.url

Demo:

>>> import requests
>>> import json
>>> headers = {'Accept': 'application/json', 'Authorization': 'Bearer <access_token>'}
>>> json_data = {'rajNames': ['WAR']}
>>> params = {'jsonRequest': json.dumps(json_data)}
>>> url = 'http://258.198.39.215:8280/areas/0.1/get/raj/name'
>>> requests.Request('GET', url, params=params, headers=headers).prepare().url
'http://258.198.39.215:8280/areas/0.1/get/raj/name?jsonRequest=%7B%22rajNames%22%3A+%5B%22WAR%22%5D%7D'

You can still eliminate the spaces used in the JSON output from json.dumps() by setting the separators argument to (',', ':') :

>>> json.dumps(json_data)
'{"rajNames": ["WAR"]}'
>>> json.dumps(json_data, separators=(',', ':'))
'{"rajNames":["WAR"]}'

but I doubt that is really needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM