我一直在尝试使用httplib2 Http类向Twilio发出API请求,无论我如何尝试设置请求,它都不会发送我的帖子DATA。我知道这一点,因为我发布到本地URL并且帖子参数是空的。这是我的代码:
_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))
我在google上找不到任何关于故障排除的内容
答案 0 :(得分:3)
Twilio在their API docs concerning POST requests中提到了这个要求:
但请务必设置HTTP Content-Type标题为
“应用程序/ x WWW的形式进行了urlencoded” 如果你是你的要求 写自己的客户。
答案 1 :(得分:0)
事实证明,'content-type'必须设置为'application / x-www-form-urlencoded'。如果有人知道原因,请告诉我。