首页 > 解决方案 > 如何使用 python 请求库发送此请求

问题描述

如何使用 python 请求库发送以下请求?

要求 :

要求

我努力了

with requests.Session() as session:
    // Some login action

    url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
    json_data = {
        "index": 0,
        "methodname": "get_enrolled",
        // And so on, from Request Body
    }

    r = session.post(url, json=json_data)

但它没有给出我想要的输出。

标签: pythonpython-requests

解决方案


1.定义一个POST请求方法

import urllib3
import urllib.parse

def request_with_url(url_str, parameters=None):
    """
    https://urllib3.readthedocs.io/en/latest/user-guide.html
    """
    http = urllib3.PoolManager()
    response = http.request("POST",
                            url_str, 
                            headers={ 
                                'Content-Type' : 'application/json' 
                            },
                            body=parameters)
    resp_data = str(response.data, encoding="utf-8")
    return resp_data

2.使用您的特定网址和参数调用该函数

json_data = {
        "index": 0,
        "methodname": "get_enrolled",
        // And so on, from Request Body
    }
key = "123456"
url = "http://somewebsite.com/lib/ajax/service.php?key={0}&info=get_enrolled".format(key)

request_with_url(url, json_data)

推荐阅读