1

Pythonを使用してurlencodedボディを正常にPOSTする多くの関数があります。しかし、私は多次元辞書である体を持っています。この辞書を使用すると、400 (不正な要求) しか取得できません。bodytmp (以下) は、Fiddler を使用して動作する body の例です。(実際の URL と本文は提供できません。) ここで見つけて現在使用している再帰的な urlencode 関数も含めましたが、成功しませんでした。

urlencoded 本文の多次元辞書を使用したこのタイプの POST リクエストの経験がある人はいますか?

ありがとうございました。(コードは読みやすくするために省略していますが、これが要点です。)

from 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): ペア = []

    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 に答える