zoukankan      html  css  js  c++  java
  • hyper发送表单数据

    前言

    某个美丽的下午,运维把服务器上的nginx升级了,http协议也变成了http2.0,我本地的requests再也连接不到服务器,然后就找到了额hyper

    但是hyper的文档写的很简单,而且相比requests来说还没那么人性化,看着demo说吧

    hyper简单使用

    from hyper import HTTP20Connection
    
    conn = HTTP20Connection(host='xxx.xxx.xxx.xxx', port=80)
    # host直接写域名或者IP地址,不要加http或https
    # port默认是443
    response = conn.request(method='POST', url='/post', body=None, headers=None)  # 你会发现这里没有data参数
    resp = conn.get_response(response)
    print(resp.read())  # 二进制,相当于requests中返回的res.content

    你会发现,没有data参数,其实我们也能想到就算写了data,最后我们进行传输的时候data也会被放到body里面,但是具体怎么转化的,我参考了requests模块

    requests模块中对data做了怎样的转换

    from collections.abc import Mapping
    from urllib.parse import urlencode
    
    
    def to_key_val_list(value):
        if value is None:
            return None
    
        if isinstance(value, (str, bytes, bool, int)):
            raise ValueError('cannot encode objects that are not 2-tuples')
    
        if isinstance(value, Mapping):
            value = value.items()
    
        return list(value)
    
    
    def _encode_params(data):
        if isinstance(data, (str, bytes)):
            return data
        elif hasattr(data, 'read'):
            return data
        elif hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data):
                if isinstance(vs, (str, bytes)) or not hasattr(vs, '__iter__'):
                    vs = [vs]
                for v in vs:
                    if v is not None:
                        result.append(
                            (k.encode('utf-8') if isinstance(k, str) else k,
                             v.encode('utf-8') if isinstance(v, str) else v))
            return urlencode(result, doseq=True)
        else:
            return data
    
    
    data = {"name": "tom", "ege": "20"}
    print(_encode_params(data))  # name=tom&ege=20

    上面这段代码是我从requests源码中截取出来的,可以直接运行,结果为name=tom&ege=20,看到这个我们就明白如何转换的了,接下来我们就可以用hyper发送表单数据了

    hyper发送表单数据

    from hyper import HTTP20Connection
    
    conn = HTTP20Connection(host='xxx.xxx.xxx.xxx', port=80)
    response = conn.request(method='POST', url='/post',
                            body='name=tom&age=20',
                            headers={'Content-Type': 'application/x-www-form-urlencoded'})
    resp = conn.get_response(response)

    一定要记得加请求头,这样可以和之前使用requests的接口进行对接了

  • 相关阅读:
    android 75 新闻列表页面
    android 74 下载文本
    android 73 下载图片
    android 72 确定取消对话框,单选对话框,多选对话框
    android 71 ArrayAdapter和SimpleAdapter
    android 70 使用ListView把数据显示至屏幕
    maven如何将本地jar安装到本地仓库
    Centos6.7搭建ISCSI存储服务器
    解决maven打包编译出现File encoding has not been set问题
    MySQL 解决 emoji表情 的方法,使用utf8mb4 字符集(4字节 UTF-8 Unicode 编码)
  • 原文地址:https://www.cnblogs.com/wuyongqiang/p/10179535.html
Copyright © 2011-2022 走看看