使用库的话,就不需要自己解析 HTTP 的字符串序列
如何对某个 URL 发送请求?
你需要: 1、url 的地址。比如 https://api.example.com/endpoint 2、请求头 Content-Type (一个 MIME),其它可能的信息(UA、Token) 3、请求体 根据 Content-Type 的类型提供对应数据 如果是 application/json 则提供 json 如果是表单,则提供 a=1&b=2 这种
工具: 1、curl 2、python:requests 3、js:axios
1、curl 构造如下命令
shell
-d, --data <data> HTTP POST data
-X, --request <method> Specify request method to use
-H, --header <header/@file> Pass custom header(s) to server(必须在 linux 下或者 gitbash 里运行,不能是 cmd,否则 json 解析出问题)
shell
curl -X POST http://localhost:5000/add -H "Content-Type: application/json" -d '{"a": 10, "b": 5}'shell
{
"result": 15.0
}备注:之所以头必须是application/json 是因为后端 Flask 的配置里直接使用了 data = request.get_json() 这要求头必须是这个
2、py requests 库
request:请求
要点:构造一个字典,把你的信息存起来
shell
import requests
url = "http://localhost:5000/add"
# 把你要发送的 JSON 组织为 Python 的字典,他会自动帮你处理
my_json = {
"a": 10, # 数字类型(非字符串!)
"b": 5
}
try:
response = requests.post(url, json=my_json)
response.raise_for_status() # 非 2xx 状态码会抛出异常
result = response.json() # 也会自动换回 JSON
print("成功!结果:", result["result"])
except requests.exceptions.HTTPError as err:
# 处理 4xx/5xx 错误
error_detail = response.json()
print(f"请求失败 [{response.status_code}]: {error_detail.get('error', 'Unknown error')}")
except Exception as e:
# 处理网络错误/JSON 解析错误等
print("发生异常:", str(e))如何搭建后端 HTTP 服务器
你也可以把它叫做叫做 API 服务,Web 服务
反正就是让前面的这几个东西能访问到
1、python Flask 框架
python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/')
def hello():
return jsonify({"message": "Calculator API is running!"})
@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
if not data or 'a' not in data or 'b' not in data:
return jsonify({"error": "Missing parameters 'a' and 'b'"}), 400
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)一般这种网络库都是通过,装饰器,把你的函数提供给库的函数的
2、fastAPI
写法类似
fastAPI 应该是需要结合 uvicorn