使用请求传递JSON函数参数

时间:2014-03-21 04:37:39

标签: php python json python-requests

我正在尝试使用位于http://api.guerrillamail.com/ajax.php的guerrillamail API,但我遇到了" set_email_user"函数,因为它需要我发布参数和函数。

我从未使用过PHP,也没有使用JSON,因此我不知道将参数发布到这样的函数的正确方法。

我正在使用python 2.7库请求来简化操作。

    s = requests.session()

    payload = {'f':'get_email_address'} 
    headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13'}
    req2 = s.post('http://api.guerrillamail.com/ajax.php', data = payload, headers = headers)
    print req2.text #prints out the current email address

    payload = {'f':'set_email_user:u\'sark\''} #here is the issue. I cannot figure out how to pass a string argument into the set_email_user function
    req = s.post('http://api.guerrillamail.com/ajax.php', data = payload, headers = headers, cookies = s.cookies)
    print req.text 

    payload = {'f':'get_email_address'}
    req2 = s.post('http://api.guerrillamail.com/ajax.php', data = payload, headers = headers, cookies = s.cookies)
    print req2.text #prints the same email address as above

1 个答案:

答案 0 :(得分:1)

我认为有点reading the docs,并且在这些线之间有点读数。顶部有一个大标题,构建了“论点”的概念;靠近底部的一些示例代码方式似乎表示如果它是数据的“查询”,则发送带有在查询字符串中编码的参数URL的GET请求,例如:

payload = {'f':'get_email_address'}
req2 = s.get('http://api.guerrillamail.com/ajax.php', params=payload)
print req2.text #prints out the current email address

...但如果您正在修改数据,请发送一个POST,其中包含在请求正文中编码的参数URL:

payload = {'f':'set_email_user', 'email_user': 'sark'}
req2 = s.post('http://api.guerrillamail.com/ajax.php', data=payload)
print req2.text #prints out the current email address

This section of the requests docs是GET参数的一个:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)

And this section用于POST数据。

最后,不要对用户代理撒谎。根据网站,API是开放的,公开的; Python应该没问题,你不需要模糊你的用户代理。