Python httplib2.Http 不发送 POST 参数
我一直在尝试用 httplib2 的 Http 类向 Twilio 发起一个 API 请求,但无论我怎么设置请求,它都不发送我的 POST 数据。我知道这一点,因为我向一个本地网址发送请求时,POST 的参数是空的。以下是我的代码:
_TWILIO_URL = 'https://api.twilio.com/2010-04-01/Accounts/%s/%s'
class Api(object):
'''
A Python interface to the Twilio API
'''
def __init__(self, AccountSid, AuthToken, From):
self.AccountSid = AccountSid
self.AuthToken = AuthToken
self.From = From
def _get_from(self, From):
"""Use the provided From number or the one defined on initialization"""
if From:
return From
else:
return self.From
def call(self, To, Url, From=None):
"""Sends a request to Twilio having it call a number; the provided URL will indicate how to handle the call"""
url = _TWILIO_URL % (self.AccountSid, 'Calls')
data = dict(From=self._get_from(From), To=To, Url=Url)
return self.request(url, body=urlencode(data))
def request(self, url, method='POST', body=None, headers={'content-type':'text/plain'}):
"""Send the actual request"""
h = Http()
h.add_credentials(self.AccountSid, self.AuthToken)
resp, content = h.request(url, method=method, body=body, headers=headers)
print content
if resp['status'] == '200':
return loads(content)
else:
raise TwilioError(resp['status'], content)
def sms(self, To, Body, From=None):
"""Sends a request to Twilio having it call a number; the provided URL will indicate how to handle the call"""
url = _TWILIO_URL % (self.AccountSid, 'SMS/Messages')
data = dict(From=self._get_from(From), To=To, Body=Body)
return self.request(url, body=urlencode(data))
我在谷歌上找不到任何关于如何解决这个问题的信息。
2 个回答
0
结果发现,'content-type' 必须设置为 'application/x-www-form-urlencoded'。如果有人知道为什么,请告诉我。
3
Twilio在他们的API文档中提到了这个要求,特别是关于POST请求的内容,链接在这里:查看文档:
如果你自己写客户端,记得要把HTTP的
Content-Type头设置为
"application/x-www-form-urlencoded"。