在下面的代码中,当在chrome上的邮递员应用程序中传递以下数据(template_data
)时,会有响应,但是当使用urllib2发布时相同的数据会出错,唯一的区别是我注意到的是required
字段即false should not be given in quotes even in postman script
其他没有响应,但urllib2中的响应失败
如果'false'在template_data中给出引号,那么结果就是400
编辑:在邮递员中,如果给出错误,则不应在引号中给出错误,因此不确定如何发送此参数
import urllib
import urllib2
def get_url_data(url, request_method, content_type, data=None,
headers={}):
method = request_method
handler = urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(handler)
if data is not None:
data = urllib.urlencode(data)
request = urllib2.Request(url, data=data,headers=headers)
request.add_header("Content-Type", content_type)
request.get_method = lambda: method
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e
print connection.code
if connection.code == 200:
resp = connection.read()
return resp
return None
form_template_url="https://example.com"
auth='sometokenid'
template_header_param = {'Authorization':auth}
template_data = {
"templateName": "somename",
"category": "Handbook",
"formTemplateDef": [{
"id": "0",
"component": "textInput",
"editable": "true",
"index": "0",
"label": "Handbook",
"description": "",
"placeholder": "TextInput",
"options": [],
"required": 'false'
}]
}
template_response = get_url_data(form_template_url,
'POST', 'application/json',
template_data, template_header_param)
答案 0 :(得分:1)
删除
data = urllib.urlencode(data)
并使用
urllib2.urlopen(req, json.dumps(data))
这应该有用。