【Python学习】Python requests.post方法中data与json参数区别

 

在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json。

datajson既可以是str类型,也可以是dict类型。

区别:

1、不管jsonstr还是dict,如果不指定headers中的content-type,默认为application/json

2、datadict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式

3、data为str时,如果不指定content-type,默认为text/plain

4、json为dict时,如果不指定content-type,默认为application/json

5、json为str时,如果不指定content-type,默认为application/json

6、用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式

 x_central_req = XCentralRequest(x_central_name='day072601', x_central_pwd='sangfor123')
    x_central_req.ssoedr()
    launch_token, launch_cookies, launch_headers = x_central_req.get_token()
    requests.adapters.DEFAULT_RETRIES = 5
    s = requests.session()
    s.keep_alive = False
    url = 'https://edrsaas.sangfor.com.cn/launch.php?s=' + str(launch_token)
    body = {
        "app_args": {
            "name": "app.web.host_mgr.host_mgr_new",
            "option": {
            }
        },
        "data": {
            "local": False
        },
        "opr": "list_zones",
        "query_id": "Query_1590748699368"
    }
    # launch_headers.update({'content-type': 'application/json'})
    resp = s.post(url=url, json=body, headers=launch_headers, cookies=launch_cookies, verify=False)
    s.close()
    print resp.json()
View Code

在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json。

datajson既可以是str类型,也可以是dict类型。

区别:

1、不管jsonstr还是dict,如果不指定headers中的content-type,默认为application/json

2、datadict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式

3、data为str时,如果不指定content-type,默认为text/plain

4、json为dict时,如果不指定content-type,默认为application/json

5、json为str时,如果不指定content-type,默认为application/json

6、用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式

 x_central_req = XCentralRequest(x_central_name='day072601', x_central_pwd='sangfor123')
    x_central_req.ssoedr()
    launch_token, launch_cookies, launch_headers = x_central_req.get_token()
    requests.adapters.DEFAULT_RETRIES = 5
    s = requests.session()
    s.keep_alive = False
    url = 'https://edrsaas.sangfor.com.cn/launch.php?s=' + str(launch_token)
    body = {
        "app_args": {
            "name": "app.web.host_mgr.host_mgr_new",
            "option": {
            }
        },
        "data": {
            "local": False
        },
        "opr": "list_zones",
        "query_id": "Query_1590748699368"
    }
    # launch_headers.update({'content-type': 'application/json'})
    resp = s.post(url=url, json=body, headers=launch_headers, cookies=launch_cookies, verify=False)
    s.close()
    print resp.json()
View Code

猜你喜欢

转载自www.cnblogs.com/gtea/p/13167985.html