urllib2 : 属性错误 'strip',

urllib2 : AttributeError 'strip',

我在调用以下函数以使用 JSON 数据

向我的端点发出 post 请求时收到 "AttributeError('strip',)"
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)

我做错了。经过如下更改后,它现在工作正常:

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)