Python network request GET and POST example

First import:

import requests
import json

Example of a GET request: 

# GET请求例子-方法:test_get [test_url是链接地址,test_data是请求参数]
def test_get(test_url, test_data):
    rep = requests.get(test_url, test_data)
    # 请求成功,打印数据:
    if rep.status_code == 200:
        # 如需将字符串解析成json,则引入 import json
        # 调用即可:json_data = json.loads(rep.text)
        print(rep.text)  # 打印返回数据
    else:
        print("请求失败,错误码:", rep.status_code)

Example of a POST request: 

# POST请求例子-方法:test_post [test_url是链接地址,test_data是请求参数]
def test_post(test_url, test_data):
    # 这里看你传的参数是啥,参数放在哪里,可以放在Params中,也可以放在body中等等

    # 如:参数为文本text,并放在Params中
    # headers = {"Content-Type": "application/x-www-form-urlencoded"}
    # rep = requests.post(test_url, test_data, headers=headers)

    # 我的例子是反正body中,并且参数是json格式
    headers = {"Content-Type": "application/json"}
    rep = requests.post(test_url, json.dumps(test_data), headers=headers)
    if rep.status_code == 200:
        # 如需将字符串解析成json,则引入 import json
        # 调用即可:json_data = json.loads(rep.text)
        print(rep.text)  # 打印返回数据
    else:
        print("请求失败,错误码:", rep.status_code)

Example of usage:

    test_url = "http://www.xxxx.com"
    test_data = {"username": "xxx", "userpwd": "xxx",  "id": 1}
    test_get(test_url,test_data)
    test_post(test_url,test_data)

Guess you like

Origin blog.csdn.net/u012402739/article/details/128611643