POST 带有 urllib2 的数据给出 400

POST data with urllib2 gives 400

在下面的代码中,当在 chrome 上的邮递员应用程序中传递以下数据(template_data)时,会有一个响应,但是使用 urllib2 发布相同的数据会出错,我注意到的唯一区别是 required 字段,即 false should not be given in quotes even in postman script 否则没有响应,但在 urllib2

中同样失败

如果 'false' 在 template_data 中给出引号,即使结果是 400

编辑:在 postman 中,如果给出错误,则不应在引号中给出 false,因此不确定如何发送此参数

 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)

删除

data = urllib.urlencode(data) 

并使用

urllib2.urlopen(req, json.dumps(data))

这应该有效。