1

我有许多函数可以使用 python 成功发布一个 urlencoded 正文。但是,我有一个多维字典的主体。使用这本字典,我只得到一个 400(错误请求)。bodytmp(下)是使用 Fiddler 工作的 body 示例。(无法提供实际的 url 和正文。)我还包括了一个递归 urlencode 函数,我在这里找到并正在使用但没有成功。

有没有人对这种类型的 POST 请求有使用 urlencoded 正文的多维字典的经验?

谢谢你。(我已经缩写了代码以使其更具可读性,但这是要点。)

从 httplib2 导入 Http 导入 httplib 导入 urllib

def postAgentRegister():

h = Http(disable_ssl_certificate_validation=True)
headers={'Content-Type':'application/x-www-form-urlencoded'}

bodytmp={"Username": "username",
        "Password": "password",
        "AccountId": "accountid",
        "PublicKey": {
        "Value1a": "32ab45cd",
        "value1b": "10001"
                     },
        "snId": "SN1",
        "IpAddresses": {
        "Value2a": ["50.156.54.45"],
        "Value2b": "null"
                   }
        }

body=recursive_urlencode(bodytmp)

try:
    response,content=h.request('https://server/endpoint','POST',headers=headers,body=body)
    conn = httplib.HTTPConnection(testserver)
    conn.request('POST', endpoint, body, headers)
    r1 = conn.getresponse()
    status = r1.status
    reason = r1.reason

except httplib.HTTPException, e:
    status= e.code

print 'status is: ', status

def recursive_urlencode(d): def recursion(d, base=None):pairs = []

    for key, value in d.items():
        if hasattr(value, 'values'):
            pairs += recursion(value, key)
        else:
            new_pair = None
            if base:
                new_pair = "%s[%s]=%s" % (base, urllib.quote(unicode(key)), urllib.quote(unicode(value)))
            else:
                new_pair = "%s=%s" % (urllib.quote(unicode(key)), urllib.quote(unicode(value)))
            pairs.append(new_pair)
    return pairs

return '&'.join(recursion(d))
4

1 回答 1

1

我是否可以建议您将正文序列化为 JSON 并在服务器接收到它时反序列化?这样你只需要做一个 url 字符串编码,而不是使用你自己的递归 url 编码。

于 2012-06-07T20:31:08.817 回答