以下代码可以作为测试接收请求的程序直接复制使用:
from flask import Flask, request
app = Flask(__name__)
@app.route('/service', methods=['POST'])
def post_route():
if request.method == 'POST':
headers = request.headers
data = request.get_json()
print'headers:',headers
print('Data Received: "{data}"'.format(data=data))
return "Request Processed.\n"
app.run()
请求命令如下:
curl -H "Content-Type:application/json" -H "Data_Type:msg" -X POST --data '{"dmac": "00:0C:29:EA:39:70", "alert_type": "alarm", "risk": 2, "trojan_name": "Trojan.qq3344", "smac": "00:0C:29:EA:39:66", "sub_alert_type": "trojan", "sport": 11, "id": "153189767146", "desc": "NoSecure 1.2 \u6728\u9a6c\u53d8\u79cd4\u8fde\u63a5\u64cd\u4f5c", "sip": "62.4.07.18", "dip": "139.82.31.91", "rule_id": 123451, "trojan_type": 4, "time": "2018-07-18 15:07:51", "dport": 61621, "detector_id": "170301020011", "os": "Windows", "trojan_id": 50030}' http://127.0.0.1:5000/service
如果是想输出http状态码,可以使用如下命令
curl -s -w %{http_code} -H "Content-Type:application/json" -H "Data_Type:msg" -X POST --data '{"dmac": "xx", "alert_type": "alarm", "risk": 2}' http://aa.bb.com/test/service/order
需要注意的是:1,--data(即-d)指定的参数必须符合json格式
2,-H 指定headers头的时候必须单个使用,即一个-H指定一个头字段信息,如上culr示例那样。
如果发送的数据存在变量,请参考这篇博客
错误写法
curl -i -X POST -H 'Content-type':'application/json' -d {"BTime":""$btime""} http://api.baidu.com
正确写法
atime=`date -d "$1" +%s`
btime=`date -d "$2" +%s`
curl -i -X POST -H "'Content-type':'application/json'" -d '{"ATime":"'$atime'","BTime":"'$btime'"}' $url
需要注意的是,json数据里变量要用''括起来
curl -w使用案例详解
1.使用touch curl-format.txt创建一个文件
2.vim curl-format.txt 输入你想打印的格式,例如
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_redirect: %{time_redirect}\n
time_pretransfer: %{time_pretransfer}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n
3.在curl-format.txt所在的文件夹下,使用命令
curl -w "@curl-format.txt" -i -X POST -H "Content-type:application/json" -d '{"projectName":"xxxx"}' http://127.0.0.1:8080/api/test/configs
4.输出如下图所示