当前位置:   article > 正文

C# HttpWebRequest使用 结合Flask作为后端进行展示_让第三方应用程序c#与flask交互

让第三方应用程序c#与flask交互

https://docs.microsoft.com/zh-cn/dotnet/api/system.net.httpwebrequest?view=netcore-3.1

C#和Flask交互的逻辑

0 测试是否可用

using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.baidu.com");
            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(wr.GetResponseStream()) )
                {
                    string result= reader.ReadToEnd();
                    System.Console.Write(result);
                }
                    
            }

        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

一 不带参数的GET请求

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://127.0.0.1:8001/test/";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url)  ;//创建请求
            request.Method = "GET"; //请求方法为GET
            HttpWebResponse res; //定义返回的response
            try
            {
                res = (HttpWebResponse)request.GetResponse(); //此处发送了请求并获得响应
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
            StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string content = sr.ReadToEnd(); //响应转化为String字符串
            Console.WriteLine(content);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

在这里插入图片描述


二 带参数的GET请求

using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace http_test


{

    public class http_test

    {
        public string GET(string url, Dictionary<String, String> param)
        {
            if (param != null) //有参数的情况下,拼接url
            {
                url = url + "?";
                foreach (var item in param)
                {
                    url = url + item.Key + "=" + item.Value + "&";
                }
                url = url.Substring(0, url.Length - 1);
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求
            request.Method = "GET"; //请求方法为GET
            HttpWebResponse res; //定义返回的response
            try
            {
                res = (HttpWebResponse)request.GetResponse(); //此处发送了请求并获得响应
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
            StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string content = sr.ReadToEnd(); //响应转化为String字符串
            return content;
        }


    }
    class Program
    {

        static void Main(string[] args)
        {
            Dictionary<string, string> param= new Dictionary<string, string>();
            // 设置参数
            param.Add("source", "D:/source/target.dicm");
            param.Add("operation", "1");
            param.Add("destination", "D:/destination/target.dicm");
            // 确定url
            string url = "http://127.0.0.1:5000/";
            http_test ht = new http_test();
            // 传送命令
            string res = ht.GET(url, param);
            // 打印返回结果
            Console.WriteLine(res);
        }

    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

在这里插入图片描述

Flask后端:

from flask import Flask,request

app = Flask(__name__)

# http://127.0.0.1:5000/?uname=xxx
@app.route('/')
def index():
    uname = None
    pwd = None
    # GET请求获取参数的第一种方式
    # uname = request.args.get('uname')

    
    # GET请求获取参数的第二种方式
    uname = request.values.get('uname')



    return f"传递过来的参数是:{uname}"


if __name__ == '__main__':
    app.run(debug=True)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
from flask import Flask,url_for
from flask_restful import Api,Resource,reqparse
app = Flask(__name__)
api = Api(app)


class Test0View(Resource):
    def get(self):
        # 1.接受json数据
        parser = reqparse.RequestParser()
        parser.add_argument('source')
        parser.add_argument('operation')
        parser.add_argument('destination')
        args = parser.parse_args()
        # 2.处理数据
        print(args)
        print(args.source)
        print(args.operation)
        print(args.destination)
        # 3.返回处理结果(json格式)
        s = "success"
        return {'res':s}



api.add_resource(Test0View,'/')

if __name__ == '__main__':
    app.run()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

在这里插入图片描述

发送一般POST请求


using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace http_test


{

    public class http_test

    {


        public void POST(string url)
        {
            // 确定上传文件
            string filePath = @"D:/1.png";
            byte[] fileContentByte = new byte[1024]; // 文件内容二进制

            // 将文件转成二进制
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            fileContentByte = new byte[fs.Length]; 
            fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
            fs.Close();

         
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            string boundary = "major";
            request.ContentType = "multipart/form-data;boundary=" + boundary;

            //定义请求流
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);

            //发送
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //获取返回值
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            Console.WriteLine(retString);

            // 关闭资源
            myStreamReader.Close();
            myResponseStream.Close();

            
        }


    }



    class Program
    {

        static void Main(string[] args)
        {
            Dictionary<string, string> param= new Dictionary<string, string>();
            string url = "http://127.0.0.1:5000/file";
            http_test ht = new http_test();
            ht.POST(url);
        
        }

    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

在这里插入图片描述

Flask后端:

import xlrd
from flask import Flask, request,url_for
from flask_restful import Api,Resource,reqparse
app = Flask(__name__)
api = Api(app)



@app.route("/file", methods=['POST'])
def filelist1():
    file = request.get_data()
    print(file)
    print(type(file))
    with open("test.jpg", "wb") as f:
        f.write(file)
    return 'OK'



api.add_resource(Test0View,'/')

if __name__ == '__main__':
    app.run()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

test.png:
在这里插入图片描述


import base64

import xlrd
from flask import Flask, request,url_for
from flask_restful import Api,Resource,reqparse
import io
from PIL import Image

app = Flask(__name__)
api = Api(app)

class TestView(Resource):

    def get(self):
        return "you use get method"

    def post(self):
        # 1.接受json数据
        parser = reqparse.RequestParser()
        print(parser)
        parser.add_argument('username')
        parser.add_argument('1.png')
        args = parser.parse_args()
        # 2.处理数据
        print(args)
        # 3.返回处理结果(json格式)
        s = "success"
        return {'res':s}

api.add_resource(TestView,'/test')

class Test0View(Resource):
    def get(self):
        # 1.接受json数据
        parser = reqparse.RequestParser()
        parser.add_argument('source')
        parser.add_argument('operation')
        parser.add_argument('destination')
        args = parser.parse_args()
        # 2.处理数据
        print(args)
        print(args.source)
        print(args.operation)
        print(args.destination)
        # 3.返回处理结果(json格式)
        s = "success"
        return {'res':s}


@app.route("/file", methods=['POST'])
def filelist1():
    file = request.get_data()
    print('file:',file)
    with open("test.dcm", "wb") as f:
        f.write(file)


    img_url = r'1.png'
    with open(img_url, 'rb') as f:
        img_stream = f.read()
        img_stream = str(img_stream)
        print(img_stream)
    return img_stream



api.add_resource(Test0View,'/')

if __name__ == '__main__':
    app.run()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71

winform framework

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1

{


    class http_test {

        public void POST(string url)
        {
            // 确定上传文件
            string filePath = @"D:/1.png";
            byte[] fileContentByte = new byte[1024]; // 文件内容二进制

            // 将文件转成二进制
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            fileContentByte = new byte[fs.Length];
            fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
            fs.Close();


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            string boundary = "major";
            request.ContentType = "multipart/form-data;boundary=" + boundary;

            //定义请求流
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);

            //发送
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //获取返回值
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();

            Console.WriteLine(retString);

            byte[] bytes = Convert.FromBase64String(retString);
            MemoryStream ms = new MemoryStream();
            ms.Write(bytes, 0, bytes.Length);
            Bitmap bmp = new Bitmap(ms);
            if (Directory.Exists("D:/test123.png"))
            {
                Directory.Delete("D:/test123.png");
            }
            bmp.Save("D:/test123.png");


            // 关闭资源
            myStreamReader.Close();
            myResponseStream.Close();


        }





    }



    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            string url = "http://127.0.0.1:5000/file";
            http_test ht = new http_test();
            ht.POST(url);

        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90

Flask.api

import base64

import xlrd
from flask import Flask, request,url_for
from flask_restful import Api,Resource,reqparse
import io
from PIL import Image

app = Flask(__name__)
api = Api(app)


class TestView(Resource):

    def get(self):
        return "you use get method"

    def post(self):
        # 1.接受json数据
        parser = reqparse.RequestParser()
        print(parser)
        parser.add_argument('username')
        parser.add_argument('1.png')
        args = parser.parse_args()
        # 2.处理数据
        print(args)
        # 3.返回处理结果(json格式)
        s = "success"
        return {'res':s}

api.add_resource(TestView,'/test')

class Test0View(Resource):
    def get(self):
        # 1.接受json数据
        parser = reqparse.RequestParser()
        parser.add_argument('source')
        parser.add_argument('operation')
        parser.add_argument('destination')
        args = parser.parse_args()
        # 2.处理数据
        print(args)
        print(args.source)
        print(args.operation)
        print(args.destination)
        # 3.返回处理结果(json格式)
        s = "success"
        return {'res':s}


@app.route("/file", methods=['POST'])
def filelist1():
    file = request.get_data()
    print('file:',file)
    with open("test.dcm", "wb") as f:
        f.write(file)


    img_url = r'1.png'
    with open(img_url, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        print(base64_data)
    return base64_data


api.add_resource(Test0View,'/')

if __name__ == '__main__':
    app.run()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

在这里插入图片描述


综合:

在这里插入图片描述

Winform

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WFM_Test001
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.baidu.com");
            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(wr.GetResponseStream()))
                {
                    string result = reader.ReadToEnd();
                    MessageBox.Show("结果:" + result);
                }

            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string url = "http://127.0.0.1:5000/test";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//创建请求
            request.Method = "GET"; //请求方法为GET
            HttpWebResponse res; //定义返回的response
            try
            {
                res = (HttpWebResponse)request.GetResponse(); //此处发送了请求并获得响应
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
            StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string content = sr.ReadToEnd(); //响应转化为String字符串
            // Console.WriteLine(content);
            MessageBox.Show("结果:" + content);
        }

        public string GET(string url, Dictionary<String, String> param)
        {
            if (param != null) //有参数的情况下,拼接url
            {
                url = url + "?";
                foreach (var item in param)
                {
                    url = url + item.Key + "=" + item.Value + "&";
                }
                url = url.Substring(0, url.Length - 1);
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求
            request.Method = "GET"; //请求方法为GET
            HttpWebResponse res; //定义返回的response
            try
            {
                res = (HttpWebResponse)request.GetResponse(); //此处发送了请求并获得响应
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
            StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string content = sr.ReadToEnd(); //响应转化为String字符串
            return content;
        }


        private void button4_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            // 设置参数
            param.Add("source", "D:/source/target.dicm");
            param.Add("operation", "1");
            param.Add("destination", "D:/destination/target.dicm");
            // 确定url
            string url = "http://127.0.0.1:5000/test2";
            // 传送命令
            string res = GET(url, param);
            // 打印返回结果
            MessageBox.Show("结果:" + res);
        }


        public String POST(string url, string file_path)
        {
            // 确定上传文件
            string filePath = file_path;
            byte[] fileContentByte = new byte[1024]; // 文件内容二进制

            // 将文件转成二进制
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            fileContentByte = new byte[fs.Length];
            fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
            fs.Close();


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            string boundary = "major";
            request.ContentType = "multipart/form-data;boundary=" + boundary;

            //定义请求流
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);

            //发送
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //获取返回值
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();

            // 关闭资源
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            string url = "http://127.0.0.1:5000/file";
            string file_path = "D:/1.png";
            string res = POST(url, file_path);
            MessageBox.Show(res);
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149

Flask

from flask import Flask, request,url_for
from flask_restful import Api,Resource,reqparse

app = Flask(__name__)
api = Api(app)

@app.route('/')
def hello_world():
    return "hello world"

@app.route('/test',methods=['GET'])
def test():
     return "hello world"


# @app.route('/upload',methods=['GET','POST'])
# def upload():
#     if request.method == 'GET':
#         return "111"
#     if request.method == 'POST':
#         return "222"

class Test0View(Resource):
    def get(self):
        # 1.接受json数据
        parser = reqparse.RequestParser()
        parser.add_argument('source')
        parser.add_argument('operation')
        parser.add_argument('destination')
        args = parser.parse_args()
        # 2.处理数据
        print(args)
        print(args.source)
        print(args.operation)
        print(args.destination)
        # 3.返回处理结果(json格式)
        return args

@app.route("/file", methods=['POST'])
def filelist1():
    file = request.get_data()
    print(file)
    print(type(file))
    with open("test.jpg", "wb") as f:
        f.write(file)
    return 'OK'


api.add_resource(Test0View,'/test2')

if __name__ == "__main__":
    app.run(debug=True)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

C# 发送POST请求带图像,待传参

public void POST(string url,string imgpath,Dictionary<string,string> send_params)
        {
            // 确定上传文件
            string filePath = imgpath;
            byte[] fileContentByte = new byte[1024]; // 文件内容二进制

            // 将文件转成二进制
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            fileContentByte = new byte[fs.Length];
            fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            var dic = new Dictionary<string, string>() {
                    {"seriesNum","xxxxxx535342423".ToString() },
                    {"para2",2.ToString() },
                    {"para3",3.ToString() },
                };
            var postData = Utils.BuildQuery(dic);//转换成:para1=1&para2=2&para3=3
            var postUrl = string.Format("{0}?{1}", url, postData);//拼接url
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
            request.AllowAutoRedirect = true;



            request.Method = "POST";
            string boundary = "major";
            request.ContentType = "multipart/form-data;boundary=" + boundary;

            //定义请求流
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);

            //发送
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //获取返回值
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            Console.WriteLine(retString);
            //MessageBox.Show(retString);
            // 关闭资源
            myStreamReader.Close();
            myResponseStream.Close();


        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("seriesNum", "xxxxxx535342423".ToString());
            string url = "http://127.0.0.1:5000/test";
            http_test ht = new http_test();


            for (int i = 0; i < 99000000000000; i++)
            {
                // ht.POST(url);
                // ht.UploadImage(@"F:\pythonDataset\CatDogDet\images\train\1.jpg");
                ht.POST(url, @"F:\pythonDataset\CatDogDet\images\train\1.jpg",param);
                Thread.Sleep(10);
            }
        
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Flask

from flask import Flask, request
from ultralytics import YOLO
import io
from PIL import Image
app = Flask(__name__)

# 1 加载模型
model = YOLO(r'F:\PycharmProjects\pythonProject\Train\Model\weights\best.pt')  # load a pretrained model (recommended for training)

# C# 访问 C# HttpWebRequest http://127.0.0.1:5000/test
@app.route("/test",methods=["GET","POST"])
def api_root():
    uname = request.args.get('seriesNum')

    fileByte = request.get_data()
    imageData = io.BytesIO(fileByte)
    img = Image.open(imageData)
    # 预测图像和训练图像大小一致
    results = model.predict(source=img, imgsz=512,
                            save=False, batch=1)  # save plotted images

    xyxy_list = []
    cls_list =[]
    conf_list = []
    for result in results:
        xyxy = result.boxes.cuda().cpu().numpy().xyxy
        cls = result.boxes.cuda().cpu().numpy().cls  # Masks object for segmentation masks outputs
        conf = result.boxes.cuda().cpu().numpy().conf  # Class probabilities for classification outputs
        xyxy_list.append(xyxy)
        cls_list.append(int(cls))
        conf_list.append(int(conf))

    res_dict = {"xyxy":xyxy_list,"conf":conf_list,"cls":cls_list}

    return str(res_dict)
if __name__ == '__main__':
    app.run()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

C# Post请求传json字符串

在这里插入图片描述

        public string Post222(string Url, string jsonParas)
        {
            string strURL = Url;
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/json";
            //设置参数,并进行URL编码 
            string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   
            byte[] payload;
            //将Json字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            request.ContentLength = payload.Length;
            //发送请求,获得请求流 
            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流
                           // String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            Stream s = response.GetResponseStream();
            //  Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();
            return postContent;//返回Json数据
        }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
        public static string ImageToBase64(string fileFullName)
        {
            try
            {
                Bitmap bmp = new Bitmap(fileFullName);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length]; ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length); ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
        private void button2_Click(object sender, EventArgs e)
        {
            string url = "http://127.0.0.1:5000/test2";
            Dictionary<string, string> param = new Dictionary<string, string>();
            // 设置参数
            param.Add("source", "D:/source/target.dicm");
            param.Add("img1", ImageToBase64(@"D:\dataset\Test\images\train\E_1-202302172236546712_DRDGR8000SW0000175+5_1_1_Org-18145657803.bmp"));
            param.Add("img2", ImageToBase64(@"D:\dataset\Test\images\train\E_1-202302172236546712_DRDGR8000SW0000175+5_1_1_Org-18145657803.bmp"));
            string data = JsonConvert.SerializeObject(param);
            Post222(url,data);

        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Flask接受

@app.route("/test2",methods=["GET","POST"])
def test2():
    try:
        data = request.get_data()
        data = json.loads(data)
        source = data['source']

        import base64
        from PIL import Image
        from io import BytesIO


        img_data = base64.b64decode(data['img1'])  # 解码时只要内容部分

        image = Image.open(BytesIO(img_data))
        image.show()


        return "success"
    except Exception as e:
        return "error"
    return str("sssss")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/748419
推荐阅读
相关标签
  

闽ICP备14008679号