requests.request方法的使用

使用requests.request发送请求,实际是使用requests.sessions.Session().request(),自动管理cookie
以下是源码:

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) <timeouts>` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      <Response [200]>
    """

    # By using the 'with' statement we are sure the session is closed, thus we
    # avoid leaving sockets open which can trigger a ResourceWarning in some
    # cases, and look like a memory leak in others.
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)

以下是例子:

import requests

url = "https://sec-m.ctrip.com/restapi/soa2/10131/json/ViewSpotSearchV1QOC"

querystring = {"Host":"sec-m.ctrip.com","Connection":"keep-alive","Pragma":"no-cache","Cache-Control":"no-cache","Accept":"application/json","cookieOrigin":"https://m.ctrip.com","Origin":"https://m.ctrip.com","User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3557.0 Mobile Safari/537.36","Content-Type":"application/json","Referer":"https://m.ctrip.com/webapp/ticket/dest/dt-上海-2/s-tickets?urltype=dt&name=上海&pagefrom=newhp_ticketIndex&searchtype=city","Accept-Encoding":"gzip, deflate, br","Accept-Language":"zh-CN,zh;q=0.9","Cookie":"_abtest_userid=50c2487b-ccaf-433f-8d0d-d29890c461ee; _ga=GA1.2.709875315.1537525410; _gid=GA1.2.16745294.1537525410; _RF1=13.67.65.168; _RSG=mf4NcnN1i67HEWHPvSsT_8; _RDG=281eecb0a9929920551fa1397940a1cdb6; _RGUID=71ac057c-665c-4a70-8fdd-d9ce59460391; MKT_Pagesource=H5; Union=OUID=&AllianceID=4897&SID=353693&SourceID=55551825&AppID=&Expires=1538130214937; _fpacid=09031077211452549306; GUID=09031077211452549306; _gat=1; Mkt_UnionRecord=[{\"aid\":\"4897\",\"timestamp\":1537525492688}]; _jzqco=|||||1.451842881.1537525415149.1537525481240.1537525492725.1537525481240.1537525492725.0.0.0.3.3; _bfa=1.1537525408919.53y3e6.1.1537525408919.1537525500093.1.5.214424"}

payload = "{\"head\":{\"cid\":\"09031077211452549306\",\"ctok\":\"\",\"cver\":\"1.0\",\"lang\":\"01\",\"sid\":\"55551825\",\"syscode\":\"09\",\"auth\":null,\"extension\":[{\"name\":\"networkstatus\",\"value\":\"None\"},{\"name\":\"protocal\",\"value\":\"https\"}]},\"ver\":\"7.13.3\",\"keyword\":\"\",\"radiusmax\":null,\"distids\":\"5_2\",\"smode\":6,\"sort\":1,\"pidx\":1,\"isintion\":true,\"psize\":20,\"isneedf\":true,\"reltype\":1,\"spara\":\"\",\"filters\":[],\"excepts\":[],\"contentType\":\"json\"}"
headers = {
    'cache-control': "no-cache",
    'postman-token': "449b7d4e-7a9c-38c7-4d1a-a7f814c2dcbd"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
# response = requests.sessions.Session().request("POST", url, data=payload, headers=headers, params=querystring, verify=False)


print(response.text)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值