Flask使用------python算法后端连接c#Winform前端
前提:我的python算法需要传出的是图片,其传入的有时是图片,有时是string(这里只放了前端代码,后端代码在之前的博客里面贴出来啦!)
前端代码:
/// <summary>
/// 通过网络地址和端口访问数据:image型--image型
/// </summary>
/// <param name="Url">网络地址</param>
/// <param name="jsonParas">json参数</param>
/// <returns></returns>
public Image RequestsPostImage(string Url, byte[] jsonParas)
{
string postContent = "";
string strUrl = Url;
Image img = null;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/json";
//设置参数,并进行URL编码
byte[] payLoad = jsonParas;
//设置请求的ContentLength
request.ContentLength = payLoad.Length;
//发送请求
Stream writer;
try
{
//获取用于写入请求数据的Stream对象
writer = request.GetRequestStream();
}
catch (Exception)
{
writer = null;
MessageBox.Show("连接服务器失败");
return null;
}
//将请求参数写入流
writer.Write(payLoad, 0, payLoad.Length);
//关闭请求流
writer.Close();
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
postContent = "default: The response is null." + "Exception: " + ex.Message;
MessageBox.Show(postContent);
}
if (response != null)
{
try
{
Stream s = response.GetResponseStream();
img = Image.FromStream(s);
}
catch (Exception e)
{
postContent = "default: The data stream is not readable." + "\r\n" + e.Message;
MessageBox.Show(postContent);
}
}
//返回JSON数据
return img;
}
/// <summary>
/// 通过网络地址和端口访问数据:string型--image型
/// </summary>
/// <param name="Url">网络地址</param>
/// <param name="jsonParas">json参数</param>
/// <returns></returns>
public Image RequestsPostString(string Url, string jsonParas)
{
string postContent = "";
string strUrl = Url;
Image img = null;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/json";
//设置参数,并进行URL编码
string paraUrlCoded = jsonParas;
byte[] payLoad;
//将json字符串转化为字节
payLoad = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的ContentLength
request.ContentLength = payLoad.Length;
//发送请求
Stream writer;
try
{
//获取用于写入请求数据的Stream对象
writer = request.GetRequestStream();
}
catch (Exception)
{
writer = null;
MessageBox.Show("连接服务器失败");
return null;
}
//将请求参数写入流
writer.Write(payLoad, 0, payLoad.Length);
//关闭请求流
writer.Close();
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
postContent = "default: The response is null." + "Exception: " + ex.Message;
MessageBox.Show(postContent);
}
if (response != null)
{
try
{
Stream s = response.GetResponseStream();
img = Image.FromStream(s);
}
catch (Exception e)
{
postContent = "default: The data stream is not readable." + "\r\n" + e.Message;
MessageBox.Show(postContent);
}
}
//返回JSON数据
return img;
}