C#与python交互(flask发送Get/Post请求)

先运行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#输出:

相关推荐
离陌在学C#7 小时前
C# 事件(Event)详解:从概念到实战
开发语言·c#
安_7 小时前
如何构建和使用向量索引?HNSW 和 IVF 有什么区别?
python·ai
rockey6279 小时前
C#脚本引擎之AScript与Flee对比
c#·.net·script·eval·动态脚本
counting money9 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
坚持学习前端日记9 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
北斗落凡尘10 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
雪碧聊技术10 小时前
安装Python(保姆级教程)
python·版本更新·python下载
++==10 小时前
JSON和Python的 四种核心容器
python·json
张龙68713 小时前
uv 全面指南:比 pip 快 100 倍的 Python 包管理器,从安装到团队落地
后端·python
@HNUSTer13 小时前
Python数据可视化科技图表绘制系列教程(八)
python·数据可视化·科技论文·专业制图·科研图表