zoukankan      html  css  js  c++  java
  • 网络编程

    建议使用requests模块,不建议使用urllib模块

    import requests

    1、发get请求
    url = 'http://api.nnzhp.cn/api/user/stu_info'

    data = {'stu_name':'小黑'} #请求的数据

    req = requests.get(url,params=data) #发get请求

    print(type(req.json())) #字典 <class 'dict'>
    print(type(req.text))    #json串 <class 'str'>

    #返回的为字典,str的json串
    #中文不会报错

    2、发post请求
    url = 'http://api.nnzhp.cn/api/user/login'

    data = {
    'username':'niuhanyang',
    'passwd':'aA123456'
    } #请求的数据
    req = requests.post(url,data) #发送post请求
    print(req.json())

    3、入参是json
    import random
    phone =random.randint(10000000000,99999999999)
    url = 'http://api.nnzhp.cn/api/user/add_stu'
    data = {
    "name":"liuyan",
    "grade":"天蝎座",
    "phone":phone,
    "sex":"男",
    "age":28,
    "addr":"hubeiwuhan"
    }

    req = requests.post(url,json=data)
    print(req.json())

    4、添加cookie
    url = 'http://api.nnzhp.cn/api/user/gold_add'
    data = {
    'stu_id':517,
    'gold':100
    }
    cookie = {'niuhanyang':'337ca4cc825302b3a8791ac7f9dc4bc6'}
    req = requests.post(url,data,cookies=cookie)
    print(req.json())

    5、获取所有信息 添加header信息,key为Referer value 为http://api.nnzhp.cn/
    url = 'http://api.nnzhp.cn/api/user/all_stu'
    header = {
    'Referer':'http://api.nnzhp.cn/'
    }
    req = requests.get(url,headers=header)
    print(req.json())

    6、上传文件
    url = 'http://api.nnzhp.cn/api/file/file_upload'
    data = {
    'file':open('day8笔记') #windows 有中文 需要encoding='utf-8'
    }
    req = requests.post(url,files=data)
    print(req.json())

    7、下载文件
    url = 'http://www.nnzhp.cn/wp-content/uploads/2018/01/soup.jpg'
    req = requests.get(url)
    fw = open('meishi.jpg','wb')
    fw.write(req.content)
  • 相关阅读:
    LeetCode 189. Rotate Array
    LeetCode 965. Univalued Binary Tree
    LeetCode 111. Minimum Depth of Binary Tree
    LeetCode 104. Maximum Depth of Binary Tree
    Windows下MySQL的安装与配置
    LeetCode 58. Length of Last Word
    LeetCode 41. First Missing Positive
    LeetCode 283. Move Zeroes
    《蚂蚁金服11.11:支付宝和蚂蚁花呗的技术架构及实践》读后感
    删除docker下的镜像
  • 原文地址:https://www.cnblogs.com/liuyanerfly/p/9056987.html
Copyright © 2011-2022 走看看