• 模拟 GET 和 POST 请求


    解析 JSON 数据的模块——JSON 模块,它用于 Python 原始类型与 JSON 类型的相互转换。


    (1).如果解析文件,可以用 dump()和 load()方法函数.转自:https://www.cnblogs.com/xiaomingzaixian/p/7286793.html

    (2).如果解析字符串,则 用下述两个函数:

    1 dumps():编码 [Python -> Json]  
    2 dict => object list, tuple => array  str => string True => true 
    3 int, float, int- & float-derived Enums => number False => false None => null 
    4  
    5 loads():解码 [Json -> Python]  
    6 object => dict array => list string => str number (int) => int  
    7 number(real) => float true =>True false => False null => None 

    模拟 GET 请求的代码

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Tue Apr  7 15:01:15 2020
     4 
     5 @author: ZKYAAA
     6 """
     7 
     8 import urllib.request
     9 import json
    10 
    11 #检验证书问题
    12 import ssl   
    13 #方法一:全局取消证书验证 
    14 #ssl._create_default_https_context=ssl._create_unverified_context 
    15 
    16 get_url="http://gank.io/api/data/"+urllib.request.quote("福利")+"/1/1"   
    17 get_resp=urllib.request.urlopen(get_url)
    18 
    19 #方法二:使用ssl创建未经验证的上下文,在urlopen()中传入上下文参数
    20 context=ssl._create_unverified_context()
    21 get_resp=urllib.request.urlopen(get_url,context=context)
    22 
    23 
    24 get_result=json.loads(get_resp.read().decode('utf-8'))
    25 #后面的参数用于格式化JSON输出格式
    26 get_result_format=json.dumps(get_result,indent=2,
    27                              sort_keys=True,ensure_ascii=False)
    28 
    29 print("get_result_format")

    模拟 POST 请求的代码

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Tue Apr  7 15:37:38 2020
     4 
     5 @author: ZKYAAA
     6 """
     7 
     8 
     9 import urllib.request
    10 import urllib.parse
    11 import json
    12  
    13 post_url="http://www.baidu.login"
    14 phone="13555555555"
    15 password="111111"
    16 values={
    17     'phone':phone,
    18     'password':password
    19 }
    20 
    21 data=urllib.parse.urlencode(values).encode(encoding='utf-8')
    22 req=urllib.request.Request(post_url,data)
    23 resp=urllib.request.urlopen(req)
    24 result=json.load(resp.read())
    25 print(json.dumps(result,sort_keys=True,indent=2,ensure_ascii=False))
  • 相关阅读:
    远程诊断DoIP
    基于linux内核包过滤技术的应用网关
    Boost内存池使用与测试
    C++ 编程规范
    大象——Thinking in UML
    C++ 创建类时常考虑的问题
    SLIP—串行线路上传输数据报的非标准协议
    神秘的程序员——编程的乐趣
    Bad Smell (代码的坏味道)
    模式与软件架构——软件架构的非功能特征
  • 原文地址:https://www.cnblogs.com/ZKYAAA/p/12654182.html
Copyright © 2020-2023  润新知