簡體   English   中英

使用urllib2進行POST數據可獲得400

[英]POST data with urllib2 gives 400

在以下代碼中,當以下數據( template_data )在chrome上的郵遞員應用程序中傳遞時,會出現響應,但使用urllib2發布時,相同的數據會出現錯誤,我唯一注意到的是required字段,即false should not be given in quotes even in postman scriptfalse should not be given in quotes even in postman script否則沒有響應,但在urllib2中同樣失敗

如果在template_data中給'false'加上引號,則結果為400

編輯:在郵遞員中,如果給出錯誤,則不應在引號中提供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))

這應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM