【问题标题】:How to make a request to the Intersango API如何向 Intersango API 发出请求
【发布时间】:2012-04-24 02:57:24
【问题描述】:

我正在尝试找出 Intersango API 的正确 URL 格式(文档很少)。我正在用 C# 对我的客户端进行编程,但我正在查看 Python example,我对实际放置在请求正文中的内容有点困惑:

def make_request(self,call_name,params):
    params.append(('api_key',self.api_key)) // <-- How does this get serialized?
    body = urllib.urlencode(params) 

    self.connect()

    try:
        self.connection.putrequest('POST','/api/authenticated/v'+self.version+'/'+call_name+'.php')
        self.connection.putheader('Connection','Keep-Alive')
        self.connection.putheader('Keep-Alive','30')
        self.connection.putheader('Content-type','application/x-www-form-urlencoded')
        self.connection.putheader('Content-length',len(body))
        self.connection.endheaders()

        self.connection.send(body)

        response = self.connection.getresponse()

        return json.load(response)
//...

这段代码我看不懂:params.append(('api_key',self.api_key))

它是某种字典,被序列化为 JSON、逗号分隔的东西,还是它究竟是如何被序列化的?当参数被编码并分配给它时,body 会是什么样子?

附:我没有任何东西可以用来运行代码,所以我可以调试它,但我只是希望这对于了解 Python 的人来说足够简单,并且他们能够告诉我那条线上发生了什么代码。

【问题讨论】:

  • 你能成功吗?我遵循了相同的步骤,但根本无法获得经过身份验证的 API 工作,得到 {"The remote server returned an error: (417) Expectation Failed."}

标签: python httprequest


【解决方案1】:

params 是 2 元素列表的列表。该列表看起来像((key1, value1), (key2, value2), ...)

params.append(('api_key',self.api_key)) 将另一个 2 元素列表添加到现有参数列表。

最后,urllib.urlencode 获取此列表并将其转换为属性 urlencoded 字符串。在这种情况下,它将返回一个字符串key1=value1&amp;key2=value2&amp;api_key=23423。如果您的键或值中有任何特殊字符,urlencode 将对它们进行 %encode。见documentation for urlencode

【讨论】:

    【解决方案2】:

    我试图让 C# 代码工作,但它一直失败并出现异常 {“远程服务器返回错误:(417) 预期失败。”}。我终于找到了问题所在。你可以深入了解它here

    简而言之,让C#访问Intersango API的方法是添加如下代码:

    System.Net.ServicePointManager.Expect100Continue = false;
    

    此代码只需要运行一次。这是一个全局设置,因此它会影响您的整个应用程序,因此请注意可能会导致其他问题。

    这是一个示例代码:

    System.Net.ServicePointManager.Expect100Continue = false;
    var address = "https://intersango.com/api/authenticated/v0.1/listAccounts.php";
    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    var postBytes = Encoding.UTF8.GetBytes("api_key=aa75***************fd65785");
    request.ContentLength = postBytes.Length;
    var dataStream = request.GetRequestStream();
    dataStream.Write(postBytes, 0, postBytes.Length);
    dataStream.Close();
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    

    【讨论】:

      【解决方案3】:

      小菜一碟 而不是params.append(('api_key',self.api_key)) 随便写:

      params['api_key']=self.api_key
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 1970-01-01
        • 2019-11-23
        • 2022-10-06
        • 2021-03-08
        • 2021-05-04
        相关资源
        最近更新 更多