简体   繁体   中英

Pass JSON function arguements using requests

I am trying to use the guerrillamail API located at http://api.guerrillamail.com/ajax.php , but I'm running into trouble with the "set_email_user" function, as it requires me to post arguments along with the function.

I have never worked with PHP, nor JSON, so I do not know the correct way to post arguments to a function like this.

I am using the python 2.7 library requests to make things easier.

    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

A bit of reading the docs , and bit of reading between the lines, I think. There's a big header at the top that builds the idea of "arguments"; some sample code way near the bottom seems to say that if it's a "query" for data, then send a GET request with the arguments URL encoded in the query string, such as:

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

… but if you're modifying data, send a POST with the arguments URL encoded in the request body:

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 is the one for the GET params:

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

And this section is for POST data.

Last, don't lie about your User-Agent. According to the site, the API is open, and public; Python should be fine, and you don't need to obscure your User-Agent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM