2011-03-05 89 views
4

我想通過SOAP POST做一個API調用,我總是收到 「TypeError:不是有效的非字符串序列或映射對象。」 @ data = urllib.urlencode(values)使用urllib2做一個SOAP POST,但我不斷收到錯誤

SM_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Header> 
    <AutotaskIntegrations xmlns="http://Autotask.net/ATWS/v1_5/"> 
     <PartnerID>partner id</PartnerID> 
    </AutotaskIntegrations> 
    </soap:Header> 
    <soap:Body> 
    <getThresholdAndUsageInfo xmlns="http://Autotask.net/ATWS/v1_5/"> 
    </getThresholdAndUsageInfo> 
    </soap:Body> 
</soap:Envelope>""" 

values = SM_TEMPLATE%() 
data = urllib.urlencode(values) 
req = urllib2.Request(site, data) 
response = urllib2.urlopen(req) 
the_page = response.read() 

任何幫助將不勝感激。

回答

5

urllib.urlencode函數期望鍵 - 值對的序列或一個映射類型等dict

>>> urllib.urlencode([('a','1'), ('b','2'), ('b', '3')]) 
'a=1&b=2&b=3' 

要執行SOAP的HTTP POST,你應該離開SM_TEMPLATE團塊原樣,並將其設置爲POST正文,然後爲POST正文的編碼和字符集添加一個Content-Type標題。例如:

data = SM_TEMPLATE 
headers = { 
    'Content-Type': 'application/soap+xml; charset=utf-8' 
    } 
req = urllib2.Request(site, data, headers) 
+0

十分感謝理解!修正了這一點,到下一個錯誤,大聲笑 – George 2011-03-06 15:56:51

+0

我還需要添加'soapAction':'GetAllItem'爲我的請求讓它工作 – kelvan 2012-05-28 23:47:19

0

查看下面的代碼作爲示例,它可以幫助您使用urllib2 for Python 2.6.6來解決您的SOAP請求。它的工作對我來說調用一個Oracle數據集成器(ODI甲骨文)。顯然,你必須適應適合你的情況爲THES的人的價值觀:

import urllib2 

url = "http://alexmoleiro.com:20910/oraclediagent/OdiInvoke?wsdl" 

post_data = """<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"> 
    <Body> 
     what_you_want_to_send_in_a_correct_format 
    </Body> 
</Envelope> 
""" 

http_headers = { 
    "Accept": "application/soap+xml,multipart/related,text/*", 
    "Cache-Control": "no-cache", 
    "Pragma": "no-cache", 
    "Content-Type": "text/xml; charset=utf-8" 

} 

request_object = urllib2.Request(url, post_data, http_headers) 

#DELETE THIS BLOCK IF YOU ARE NOT USING PROXIES 
http_proxy_server = "10.1.2.3" 
http_proxy_port = "8080" 
http_proxy_realm = http_proxy_server 
http_proxy_full_auth_string = "http://%s:%s" % (http_proxy_server, http_proxy_port) 
proxy = urllib2.ProxyHandler({'http': http_proxy_full_auth_string}) 
opener = urllib2.build_opener(proxy) 
urllib2.install_opener(opener) 
#END OF --> DELETE THIS BLOCK IF YOU ARE NOT USING PROXIES 

response = urllib2.urlopen(request_object) 
html_string = response.read() 
print html_string 

任何反饋將:-)

相關問題