专业的编程技术博客社区

网站首页 > 博客文章 正文

Python-自己动手优化接口HTTP报文信息打印

baijin 2024-11-04 11:38:39 博客文章 9 ℃ 0 评论

前言


我们知道Python发送网络HTTP请求非常简单,只需要调用requests库,即可完成一个HTTP请求,但是它自身打印出来的结果还是不太友好。

我们可以在此基础上,打印一些常用的HTTP报文信息,方便我们自己熟悉接口的完整交互。



GET请求例子


import json
from urllib.parse import urlencode
import requests

# 格式化json
def format_json(json_data):
    if isinstance(json_data, dict):
        return json.dumps(json_data, indent=4).encode('utf-8').decode('unicode_escape')
    else:
        return json.dumps(json.loads(json_data), indent=4).encode('utf-8').decode('unicode_escape')

# resp_type: 响应的类型是json串,还是非json串
# show_respbody: 是否打印响应的Body正文
def get_request(url, headers, params, resp_type=None, show_respbody=True):
    print("\n1.请求URL:")

    if len(params) == 0:
        print("%s" % (url))
    else:
        print("%s?%s" % (url, urlencode(params)))

    print("\n2.请求方式:")
    print("GET")
    print("\n3.请求headers:")
    print("%s" % (headers))

    try:
        r = requests.get(url, headers=headers, params=params)

        r_status = r.status_code
        r_body = r.text
    except Exception as e:
        print("\n4.请求异常:")
        print("{}".format(str(e)))
        return 500, None

    print("\n4.响应状态码:")
    print("%s" % (r_status))

    print("\n5.响应结果:")

    if show_respbody:
        if resp_type == "json":
            r_body = format_json(r_body)
            print("%s" % (r_body))
        else:
            if '{"' in r_body:
                r_body = format_json(r_body)
                print("%s" % (r_body))
            else:
                print("%s" % (r_body))
    else:
        print("配置不显示响应信息")

    return r_status, r_body


打印HTTP报文信息


1.请求URL:
http://10.10.10.10:8083/query/template?token=123

2.请求方式:
GET

3.请求headers:
{'Content-Type': 'text/plain;charset=UTF-8'}

4.响应状态码:
200

5.响应结果:
{
    "returnCode": "000000",
    "description": "请求成功"
}


结束


当你想了解接口是否符合规范,通过上面的小小例子,这样是不是更加直观了。


如果喜欢本文的话,请关注+收藏,谢谢。


本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表