1. 接口交互

1. get

通过params方式传递参数,可以通过浏览器模拟

2.post

四种方式包括:

  • application/x-www-form-urlencoded (URL encoded)
  • multipart/form-data (键值对型数据)
  • application/json (Json 类型数据)
  • text/xml (xml)

application/x-www-form-urlencoded

浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。其传参方式为 key=value&key=value&key=value.. 也就意味着是以字符串形式传输

  1. # 这里面是给data=传入参数,参数格式是 Python dict字典
  2. requests.post(url="http://httpbin.org/post",data=p_data,
  3. headers={"Content-type": "application/x-wwww-form-urlencoded"}).json()

multipart/form-data

使用表单上传文件时,必须让 form 的 enctyped 等于这个值

# 和上面的一样也是给data=传参,不同的是数据的编码方式不同。

from requests_toolbelt import MultipartEncoder

m = MultipartEncoder(
    fields={
        'field0': 'value1', 'field1': 'value2', 'field2': 
            ('filename', open('data.txt', 'rb'), 'text/plain')
    }
 )
requests.post(url="http://httpbin.org/post",data=m, 
              headers={"Content-type": "multipart/form-data"}).json()

application/json

消息主体是序列化后的 JSON 字符串

# 这里面是给json=传入参数,参数的格式 Json 字符串,所以需要使用 json.dumps(), 
# 将 Python dict 转 Json 字符串(其实就是 Python 的 str 类型,但是接收方会对字符串进行 Json 解码)

import json
p_data = json.dumps(p_data)
requests.post(url="http://httpbin.org/post",json=p_data, 
              headers={"Content-type": "application/json"}).json()

text/xml

是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范,不常用。

# 和前面几个的一样也是给data=传参,参数类型是字符串,但是必须按照 xml 的语法写。

p_data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>'

requests.post(url="http://httpbin.org/post",data=p_data, 
              headers={"Content-type": "text/xml"}).json()