dtsps2098 2014-03-21 04:37
浏览 105
已采纳

使用请求传递JSON函数参数

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
  • 写回答

1条回答 默认 最新

  • dougu6815 2014-03-21 05:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊