requests模块03——模拟通过multipart/form-data格式发送post请求

前言:愿每个晴朗的日子,你都能开怀大笑~

方式一:导入OrderedDict模块

from collections import OrderedDict

headerinfos_01 = {
    'Accept':'application/json, text/javascript, */*; q=0.01',
    'X-Requested-With':'XMLHttpRequest',
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
}

get_params_03 = { "c":"post", "a":"doadd", "_json":"1", "fid":"80" } from_data1 = OrderedDict( [ ("atc_title", (None, 'newdream1111')), ("atc_content", (None, 'newdream1111')), ('pid', (None, '')), ('tid', (None, '')), ('special', (None, 'default')), ('reply_notice', (None, '1')), ('csrf_token', (None, value)) ] ) #OrderedDict模块的应用
 response04 = session_req.post( url='http://47.107.178.45/phpwind/index.php', #登录 params = get_params_03, headers = headerinfos, files = from_data1 ) print( response04.content.decode('utf-8') )

方式二:

1.引入multipartformdata类

class MultipartFormData(object):
    """multipart/form-data格式转化"""

    @staticmethod
    def format(data, boundary="----WebKitFormBoundary7MA4YWxkTrZu0gW", headers={}):
        """
        form data
        :param: data:  {"req":{"cno":"18990876","flag":"Y"},"ts":1,"sig":1,"v": 2.0}
        :param: boundary: "----WebKitFormBoundary7MA4YWxkTrZu0gW"
        :param: headers: 包含boundary的头信息;如果boundary与headers同时存在以headers为准
        :return: str
        :rtype: str
        """
        # 从headers中提取boundary信息
        if "content-type" in headers:
            fd_val = str(headers["content-type"])
            if "boundary" in fd_val:
                fd_val = fd_val.split(";")[1].strip()
                boundary = fd_val.split("=")[1].strip()
            else:
                raise Exception("multipart/form-data头信息错误,请检查content-type key是否包含boundary")
        # form-data格式定式
        jion_str = '--{}\r\nContent-Disposition: form-data; name="{}"\r\n\r\n{}\r\n'
        end_str = "--{}--".format(boundary)
        args_str = ""

        if not isinstance(data, dict):
            raise Exception('multipart/form-data参数错误,data参数应为dict类型')
        for key, value in data.items():
            args_str = args_str + jion_str.format(boundary, key, value)

        args_str = args_str + end_str.format(boundary)
        args_str = args_str.replace("\'", "\"")
        return args_str

2.header中新增

'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryCBnR4ejvQPQNsCEC'

3.创建对象

m = MultipartFormData.format(data=data, headers=headers_info)

4.最后引用

session_03.post(url='http://47.107.178.45/phpwind/index.php', data=m, params=para_03,cookies =cookie,headers=headers_info)

 

你可能感兴趣的:(requests模块03——模拟通过multipart/form-data格式发送post请求)