先运行python,再运行C#
**ps: 注意修改端口号**
python发送Get/Post请求
python
# -*- coding: utf-8 -*-
# Time : 2024/1/25 15:52
# Author : YY
# File : post_test.py
# Content:提交数据给客户端
from flask import Flask, request, jsonify, redirect, render_template, url_for
app = Flask(__name__) # 实例化对象
@app.route('/test/stats/', methods=["POST", "GET"])
def display():
try:
print('request method:', request.method)
if request.method == "POST":
data = request.get_json() # 传入的数据
print("data:", data)
get_id = data.get("id")
get_Seconds = int(data.get("Seconds"))
if get_id is None or get_Seconds is None:
return jsonify(msg="缺少参数")
elif get_id == '500' and get_Seconds > 240:
r = {'flag': '1'} # 假设这是你的字典
# 检查键 'flag' 是否存在
if 'flag' in r:
print(r['flag']) # 如果键存在,则打印对应的值
return jsonify(r)
else:
print("键 'flag' 不存在于字典中。") # 如果键不存在,则打印错误消息
return jsonify({'flag': '0'})
else:
return jsonify({'error': 'Invalid data'})
elif request.method == "GET":
return "Hello World!"
except Exception as e:
print(e)
return jsonify(msg="出错了,请查看是否正确访问")
if __name__ == '__main__':
# app.run() # 默认本主机访问http://127.0.0.1:5000/
# app.run(host="0.0.0.0") # 任何主机都可以访问
app.run(port='5012') # 修改端口号
C#发送Get/Post请求
csharp
using System.Threading.Tasks;
using System.Net.Http;
using System.Collections.Generic;
using Newtonsoft.Json;
using System;
using System.Text;
namespace MyFlask
{
class Program
{
//post 上传数据并读取相应内容
public async Task<string> PostWebContentAsync(string url)
{
string responseBody = "";
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{"id", "500"},
{"Seconds", "250"}
};
string json = JsonConvert.SerializeObject(values); // 序列化字典
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
try
{
if (response.IsSuccessStatusCode)
{
responseBody = await response.Content.ReadAsStringAsync(); // 读取响应内容
// 处理响应内容
var jsonResult = JsonConvert.DeserializeObject<dynamic>(responseBody); // 解析JSON
// 输出password字段
if (jsonResult.flag != null)
{
Console.WriteLine("flag: " + jsonResult.flag);
}
else
{
Console.WriteLine("flag not found in the response.");
}
}
else
{
// 处理错误响应
Console.WriteLine($"Error: {response.StatusCode}");
}
}
catch (Exception ex)
{
// 处理异常
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("非静态任务完成。");
return responseBody; // 返回响应内容
}
//get 获取数据
public async Task<string> GetWebContentAsync(string url)
{
string responseContent = "";
//Task.Delay(1000).Wait(); // 模拟长时间运行的操作
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url); // 发送GET请求
try
{
if (response.IsSuccessStatusCode)
{
responseContent = await response.Content.ReadAsStringAsync(); // 读取响应内容
// 处理响应内容
System.Console.WriteLine("response:" + response);
System.Console.WriteLine("responseContent:" + responseContent);
}
else
{
// 处理错误响应
Console.WriteLine($"Error: {response.StatusCode}");
}
}
catch (Exception ex)
{
// 处理异常
System.Console.WriteLine("Exception:" + ex);
}
System.Console.WriteLine("非静态任务完成。");
return responseContent;
}
static void Main(string[] args)
{
System.Console.WriteLine("start...");
string url = "http://127.0.0.1:5012/test/stats/";
Program myInstance = new Program();// 创建MyClass的一个实例
//选择flask方式
string expression = "post";
//string expression = "get";
System.Console.WriteLine("执行非静态任务。");
// 创建一个Task来执行非静态方法
switch (expression)
{
case "post":
// 调用非静态方法
Task taskPost = myInstance.PostWebContentAsync(url);// 创建一个Task来执行非静态方法
taskPost.Wait();// 使用await等待Task完成
break;
case "get":
Task taskGet = myInstance.GetWebContentAsync(url);// 创建一个Task来执行非静态方法
taskGet.Wait();// 使用await等待Task完成
break;
default:
// 默认代码块
Task task = myInstance.GetWebContentAsync(url);
task.Wait();// 使用await等待Task完成
break;
}
//main其他方法
System.Console.WriteLine("Main方法继续执行。");
System.Console.WriteLine("end...");
}
}
}
python输出:
c#输出: