1. 程式人生 > >C# GET/POST FLASK資料交換

C# GET/POST FLASK資料交換

C#端:

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

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

        public static string PostHttpResponse(string url)
        {
            string responseResult = String.Empty;

            //string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //獲取內容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                responseResult = reader.ReadToEnd();
            }
            return responseResult;
        }

        public static string GetHttpResponse(string url, int Timeout)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = Timeout;

            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;
        }


        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是傳送HTTPS請求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //設定代理UserAgent和超時
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //傳送POST資料  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }


        /// <summary>
        /// 獲取請求的資料
        /// </summary>
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();

            }
        }

        //private void btn_get_Click(object sender, EventArgs e)
        //{
        //    string url = "http://127.0.0.1:5000/";
        //    string res = GetHttpResponse(url, 6000);
        //    textBox1.Text = res;
        //}

        private void btn_post_Click(object sender, EventArgs e)
        {
            string url = "http://127.0.0.1:5000/postdata";
            string p;
            //引數p
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("key1", "ddd");
            //http請求
            System.Net.HttpWebResponse res = CreatePostHttpResponse(url, parameters, 3000, null, null);
            if (res == null)
            {
                //.Redirect("RequestFailed.aspx?result=出錯了,可能是由於您的網路環境差、不穩定或安全軟體禁止訪問網路,您可在網路好時或關閉安全軟體在重新訪問網路。");
            }
            else
            {
                //獲取返回資料轉為字串
                string mes = GetResponseString(res);
                txt_total.Text = mes;
               // T model = JsonHelper.DeserializeJsonToObject<T>(mes);
            }
        }
    }


}

python端:

from flask import Flask
from flask import request
import json

app = Flask(__name__)


def add(a, b):
    return a+b

@app.route('/')
def test():
    t = {}
    s = 3
    t[0] = s
    return json.dumps(t, ensure_ascii=False)

@app.route('/postdata', methods=['POST'])
def postdata():
    print (request.form.get('key1'))
    return  "ok"





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

參考連結:

https://blog.csdn.net/mrli113/article/details/53200557

https://segmentfault.com/a/1190000002910103