2017-06-14 59 views
0

我得到「AttributeError的(‘條’)」,而調用下面的函數使POST請求我的端點JSON數據的urllib2:AttributeError的「帶」,

def makePostRequest(apiUrl, body): 
try: 

     jsondata = json.dumps(body) 
     jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes 
     len(jsondataasbytes) 
     req = urllib2.Request(apiUrl, jsondata, {'Content-Type': 'application/json', 
               'Content-Length': jsondataasbytes}) 
     try: 
      response = urllib2.Request(req, jsondataasbytes) 
      response_data = response.read() 
      print (response_data) 
     except Exception as err: 
      print ("Error: %s", err) 
except Exception as error: 
     print ("error in makePostRequest: ", error) 
+0

您可以發佈完整的錯誤堆棧跟蹤:這是做一些改變如下現在後工作正常? – zwer

+0

@zwer我只是得到這個錯誤:「('錯誤:%s',AttributeError('strip',))」 – iamgroot

回答

0

我是做了錯誤的方式。

def makePostRequest(apiUrl, body): 
try: 
    req = urllib2.Request(apiUrl) 
    req.add_header('Content-Type', 'application/json') 
    jsondata = json.dumps(body) 

    jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes 
    req.add_header('Content-Length', len(jsondataasbytes)) 
    try: 
     response = urllib2.urlopen(req, jsondataasbytes) 
     response_data = response.read() 
     print (response_data) 
    except Exception as err: 
      print ("Error: %s", err) 
except Exception as error: 
     print ("error in makePostRequest: ", error)