先运行python,再运行C#
**ps: 注意修改端口号**
python发送Get/Post请求
# -*- 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_forapp = 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请求
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#输出: