python远程服务调用

一 GET请求

设置headers,user-agent用来模拟浏览器。cookie是远程服务需要校验的认证信息:比如token。

请求:requests.get(url, headers=headers, params=params, verify=False),params是get请求时的form表单里的参数,verify=False设置为false即可。

得到响应结果response后,可以转化为json格式进一步处理。

 

import requests

if __name__ == "__main__":
    Cookie = "" #认证信息
    url = "" #请求api地址
    headers = { 
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36", 
        "Cookie": Cookie
    }
    for fileId in fileIds:
        params = {"fileId": fileId}
        response = requests.get(url, headers=headers, params=params, verify=False)
        result = response.json()
        code = result["code"]
        if code == 200:
            if result["data"] is not None:
                data = result["data"]
                print(data["videoPlayUrl"])

二 POST请求

post与get除了请求方式不同,请求时参数的格式也不同,post请求参数为json。

requests.post(url, json=param, headers=headers, verify=False)

 

import requests

if __name__ == "__main__":
     url = 'xxx'
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Cookie": "xxx"}
        param = {
            "code": redeemCode,
            "page": 1,
            "size": 10
        }
        response = requests.post(url, json=param, headers=headers, verify=False)
        result = response.json()
        code = result["code"]
        if code == 200:
            if result["data"] is not None and isinstance(result["data"], dict):
                print(redeemCode + " 查询成功")

 

posted @ 2024-02-28 17:47  江湖凶险  阅读(22)  评论(0编辑  收藏  举报