python实现以application/json格式为请求体的http post请求

315 阅读1分钟

www.cnblogs.com/kristin/p/1…

  • Python实现脚本请求接口并以中文打印接口返回的数据

    import json import requests

    url = "https://....//Api/User/...." values = {'token':'4CAC044621D1EE5DC8D573BA019EE4FD2CD87859','lang':'jp'}

    打印values的数据类型,输出<class 'dict'>

    print(type(values)) print(values)

    json.dump将python对象编码成json字符串

    values_json = json.dumps(values)

    打印编码成json字符串的values_json的数据类型,输出<class 'str'>

    print(type(values_json)) print(values_json)

    requests库提交数据进行post请求

    req = requests.post(url, data=values_json)

    打印Unicode编码格式的json数据

    print(req.text)

    使用json.dumps()时需要对象相应的类型是json可序列化的

    change = req.json()

    json.dumps序列化时对中文默认使用ASCII编码,如果无任何配置则打印的均为ascii字符,输出中文需要指定ensure_ascii=False

    new_req = json.dumps(change, ensure_ascii=False)

    打印接口返回的数据,且以中文编码

    print(new_req)

  • 使用到的函数

json.dump() 将python对象编码成json字符串

requests.post(url, data) requests库提交数据进行post请求

req.json() 在使用json.dumps前将对象req进行json可序列化

json.dumps(change, ensure_ascii=False) json.dumps序列化数据并输入中文编码数据

  • 脚本执行过程报错记录,requests爬虫时开启代理会报以下错误

requests.exceptions.SSLError: HTTPSConnectionPool(host='api.****.cn', port=443):Max retries exceeded with url: //Api/User/getStaffList (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))