2011-03-22 55 views
2

我一直在嘗試使用httplib2 Http類向Twilio發出API請求,無論我如何設置請求,它都不會發送我的發佈數據。我知道這一點,因爲我發佈到本地URL並且帖子參數是空的。這裏是我的代碼:Python httplib2.Http不發送發佈參數

_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)) 

我找不到任何谷歌談論故障排除

回答

0

事實證明,在「內涵式」已被設置爲「應用程序/ x-WWW的形式-urlencoded」。如果有人知道爲什麼,請告訴我。

+0

因爲那是什麼內容類型IS。雖然它可能是POST請求中最明顯的內容類型(當從html表單使用時),但POST可以用於其他內容,如html,xml,pdf等......甚至html表單也不僅限於這種類型(見http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4)。以這種方式來看待:你發佈一個「文件」,你必須聲明它是什麼類型。 – Steven 2011-03-22 17:04:15