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);
}
}
}
}
}
一 不带参数的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);
}
}
}
二 带参数的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);
}
}
}
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)
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()
发送一般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);
}
}
}
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()
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()
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);
}
}
}
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()
综合:
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);
}
}
}
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)
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¶2=2¶3=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();
}
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);
}
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()
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数据
}
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;
}
}
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);
}
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")