Ver Fonte

增加测试功能。

Klosszhu há 2 anos atrás
pai
commit
a4b6b68179

+ 266 - 0
Fine.OPCDaClient9000/App/IHttpMethod.cs

@@ -0,0 +1,266 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.IO;
+using System.Net;
+using System.Net.Http;
+
+namespace FaceppSDK
+{
+    #region 提交方式
+    public class HttpMethods 
+    {
+    
+        #region POST
+        /// <summary>
+        /// HTTP POST方式请求数据
+        /// </summary>
+        /// <param name="url">URL.</param>
+        /// <param name="param">POST的数据</param>
+        /// <returns></returns>
+        public virtual string HttpPost(string url, string param)
+        {
+            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
+            request.Method = "POST";
+            request.ContentType = "application/x-www-form-urlencoded";
+            request.Accept = "*/*";
+            request.Timeout = 150000;
+            request.AllowAutoRedirect = false;
+            StreamWriter requestStream = null;
+            WebResponse response = null;
+            string responseStr = null;
+
+            try
+            {
+                requestStream = new StreamWriter(request.GetRequestStream());
+                requestStream.Write(param);
+                requestStream.Close();
+
+                response = request.GetResponse();
+                if (response != null)
+                {
+                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
+                    responseStr = reader.ReadToEnd();
+                    reader.Close();
+                }
+            }
+            catch (Exception)
+            {
+                Console.WriteLine("api 访问错误");
+            }
+            finally
+            {
+                request = null;
+                requestStream = null;
+                response = null;
+            }
+
+            return responseStr;
+        }
+        #endregion
+
+        #region Get
+        /// <summary>
+        /// HTTP GET方式请求数据.
+        /// </summary>
+        /// <param name="url">URL.</param>
+        /// <returns></returns>
+        public virtual string HttpGet(string url)
+        {
+            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
+            request.Method = "GET";
+            //request.ContentType = "application/x-www-form-urlencoded";
+            request.Accept = "*/*";
+            request.Timeout = 150000;
+            request.AllowAutoRedirect = false;
+
+            WebResponse response = null;
+            string responseStr = null;
+
+            try
+            {
+                response = request.GetResponse();
+
+                if (response != null)
+                {
+                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
+                    responseStr = reader.ReadToEnd();
+                    reader.Close();
+                }
+            }
+            catch (Exception)
+            {
+                Console.WriteLine("api 访问错误");
+            }
+            finally
+            {
+                request = null;
+                response = null;
+            }
+
+            return responseStr;
+        }
+        #endregion
+
+        #region Post With Pic
+        private string HttpPost(string url, IDictionary<object, object> param, string filePath)
+        {
+            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
+            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
+
+            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
+            wr.ContentType = "multipart/form-data; boundary=" + boundary;
+            wr.Method = "POST";
+            wr.KeepAlive = true;
+            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
+
+            Stream rs = wr.GetRequestStream();
+            string responseStr = null;
+
+            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
+            foreach (string key in param.Keys)
+            {
+                rs.Write(boundarybytes, 0, boundarybytes.Length);
+                string formitem = string.Format(formdataTemplate, key, param[key]);
+                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
+                rs.Write(formitembytes, 0, formitembytes.Length);
+            }
+            rs.Write(boundarybytes, 0, boundarybytes.Length);
+
+            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
+            string header = string.Format(headerTemplate, "img", filePath, "text/plain");
+            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
+            rs.Write(headerbytes, 0, headerbytes.Length);
+
+            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
+            byte[] buffer = new byte[4096];
+            int bytesRead = 0;
+            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
+            {
+                rs.Write(buffer, 0, bytesRead);
+            }
+            fileStream.Close();
+
+            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
+            rs.Write(trailer, 0, trailer.Length);
+            rs.Close();
+
+            WebResponse wresp = null;
+            try
+            {
+                wresp = wr.GetResponse();
+                Stream stream2 = wresp.GetResponseStream();
+                StreamReader reader2 = new StreamReader(stream2);
+                responseStr = reader2.ReadToEnd();
+                Console.WriteLine(string.Format("File uploaded, server response is: {0}", responseStr));
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine("Error uploading file", ex);
+                if (wresp != null)
+                {
+                    wresp.Close();
+                    wresp = null;
+                }
+            }
+            finally
+            {
+                wr = null;
+            }
+            return responseStr;
+        }
+        #endregion
+
+        #region Post With Pic
+        /// <summary>
+        /// HTTP POST方式请求数据(带图片)
+        /// </summary>
+        /// <param name="url">URL</param>       
+        /// <param name="param">POST的数据</param>
+        /// <param name="fileByte">图片</param>
+        /// <returns></returns>
+        public virtual string HttpPost(string url, IDictionary<object, object> param, byte[] fileByte)
+        {
+            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
+            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
+
+            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
+            wr.ContentType = "multipart/form-data; boundary=" + boundary;
+            wr.Method = "POST";
+            wr.KeepAlive = true;
+            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
+
+            Stream rs = wr.GetRequestStream();
+            string responseStr = null;
+
+            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
+            foreach (string key in param.Keys)
+            {
+                rs.Write(boundarybytes, 0, boundarybytes.Length);
+                string formitem = string.Format(formdataTemplate, key, param[key]);
+                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
+                rs.Write(formitembytes, 0, formitembytes.Length);
+            }
+            rs.Write(boundarybytes, 0, boundarybytes.Length);
+
+            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
+            string header = string.Format(headerTemplate, "img", fileByte, "text/plain");//image/jpeg
+            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
+            rs.Write(headerbytes, 0, headerbytes.Length);
+
+            rs.Write(fileByte, 0, fileByte.Length);
+
+            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
+            rs.Write(trailer, 0, trailer.Length);
+            rs.Close();
+
+            WebResponse wresp = null;
+            try
+            {
+                wresp = wr.GetResponse();
+                Stream stream2 = wresp.GetResponseStream();
+                StreamReader reader2 = new StreamReader(stream2);
+                responseStr = reader2.ReadToEnd();
+                Console.WriteLine(string.Format("File uploaded, server response is: {0}", responseStr));
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine("Error uploading file", ex);
+                if (wresp != null)
+                {
+                    wresp.Close();
+                    wresp = null;
+                }
+            }
+            finally
+            {
+                wr = null;
+            }
+            return responseStr;
+        }
+        #endregion
+    }
+    #endregion
+
+    #region 枚举
+    /// <summary>
+    /// 请求方式
+    /// </summary>
+    public enum Method
+    {
+        GET,
+        POST,
+        DELETE
+    }
+
+    /// <summary>
+    /// 返回格式
+    /// </summary>
+    public enum Format
+    {
+        xml,
+        json,
+    }
+    #endregion
+}

+ 1 - 0
Fine.OPCDaClient9000/Fine.OPCDaClient9000.csproj

@@ -99,6 +99,7 @@
     <Compile Include="App\AppHandle.cs" />
     <Compile Include="App\BaseService.cs" />
     <Compile Include="App\Common\AppUtil.cs" />
+    <Compile Include="App\IHttpMethod.cs" />
     <Compile Include="App\ItemService.cs" />
     <Compile Include="App\MachineService.cs" />
     <Compile Include="App\TreePathView.cs" />

+ 61 - 8
Fine.OPCDaClient9000/TestForm.Designer.cs

@@ -37,9 +37,14 @@ namespace Fine.OPCDaClient9000
             this.button1 = new System.Windows.Forms.Button();
             this.groupBox3 = new System.Windows.Forms.GroupBox();
             this.richTextBox1 = new System.Windows.Forms.RichTextBox();
+            this.groupBox4 = new System.Windows.Forms.GroupBox();
+            this.richTextBox2 = new System.Windows.Forms.RichTextBox();
+            this.richTextBox3 = new System.Windows.Forms.RichTextBox();
+            this.label1 = new System.Windows.Forms.Label();
             this.groupBox1.SuspendLayout();
             this.groupBox2.SuspendLayout();
             this.groupBox3.SuspendLayout();
+            this.groupBox4.SuspendLayout();
             this.SuspendLayout();
             // 
             // listBox1
@@ -50,15 +55,18 @@ namespace Fine.OPCDaClient9000
             this.listBox1.Location = new System.Drawing.Point(6, 27);
             this.listBox1.Name = "listBox1";
             this.listBox1.ScrollAlwaysVisible = true;
-            this.listBox1.Size = new System.Drawing.Size(362, 580);
+            this.listBox1.Size = new System.Drawing.Size(386, 580);
             this.listBox1.TabIndex = 8;
+            this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
             // 
             // groupBox1
             // 
+            this.groupBox1.Controls.Add(this.label1);
+            this.groupBox1.Controls.Add(this.richTextBox3);
             this.groupBox1.Controls.Add(this.listBox1);
             this.groupBox1.Location = new System.Drawing.Point(13, 26);
             this.groupBox1.Name = "groupBox1";
-            this.groupBox1.Size = new System.Drawing.Size(398, 631);
+            this.groupBox1.Size = new System.Drawing.Size(398, 824);
             this.groupBox1.TabIndex = 9;
             this.groupBox1.TabStop = false;
             this.groupBox1.Text = "查询结果";
@@ -70,7 +78,7 @@ namespace Fine.OPCDaClient9000
             this.groupBox2.Controls.Add(this.textBox1);
             this.groupBox2.Location = new System.Drawing.Point(417, 26);
             this.groupBox2.Name = "groupBox2";
-            this.groupBox2.Size = new System.Drawing.Size(583, 169);
+            this.groupBox2.Size = new System.Drawing.Size(583, 92);
             this.groupBox2.TabIndex = 10;
             this.groupBox2.TabStop = false;
             this.groupBox2.Text = "查询";
@@ -105,35 +113,76 @@ namespace Fine.OPCDaClient9000
             // groupBox3
             // 
             this.groupBox3.Controls.Add(this.richTextBox1);
-            this.groupBox3.Location = new System.Drawing.Point(417, 202);
+            this.groupBox3.Location = new System.Drawing.Point(417, 282);
             this.groupBox3.Name = "groupBox3";
-            this.groupBox3.Size = new System.Drawing.Size(583, 455);
+            this.groupBox3.Size = new System.Drawing.Size(751, 568);
             this.groupBox3.TabIndex = 11;
             this.groupBox3.TabStop = false;
             this.groupBox3.Text = "结果";
             // 
             // richTextBox1
             // 
-            this.richTextBox1.Location = new System.Drawing.Point(7, 28);
+            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
+            this.richTextBox1.Location = new System.Drawing.Point(3, 24);
             this.richTextBox1.Name = "richTextBox1";
-            this.richTextBox1.Size = new System.Drawing.Size(570, 421);
+            this.richTextBox1.Size = new System.Drawing.Size(745, 541);
             this.richTextBox1.TabIndex = 0;
             this.richTextBox1.Text = "";
             // 
+            // groupBox4
+            // 
+            this.groupBox4.Controls.Add(this.richTextBox2);
+            this.groupBox4.Location = new System.Drawing.Point(420, 124);
+            this.groupBox4.Name = "groupBox4";
+            this.groupBox4.Size = new System.Drawing.Size(748, 152);
+            this.groupBox4.TabIndex = 12;
+            this.groupBox4.TabStop = false;
+            this.groupBox4.Text = "输入参数";
+            // 
+            // richTextBox2
+            // 
+            this.richTextBox2.Dock = System.Windows.Forms.DockStyle.Fill;
+            this.richTextBox2.Location = new System.Drawing.Point(3, 24);
+            this.richTextBox2.Name = "richTextBox2";
+            this.richTextBox2.Size = new System.Drawing.Size(742, 125);
+            this.richTextBox2.TabIndex = 0;
+            this.richTextBox2.Text = "";
+            // 
+            // richTextBox3
+            // 
+            this.richTextBox3.Location = new System.Drawing.Point(0, 655);
+            this.richTextBox3.Name = "richTextBox3";
+            this.richTextBox3.Size = new System.Drawing.Size(392, 163);
+            this.richTextBox3.TabIndex = 9;
+            this.richTextBox3.Text = "";
+            // 
+            // label1
+            // 
+            this.label1.AutoSize = true;
+            this.label1.Location = new System.Drawing.Point(6, 622);
+            this.label1.Name = "label1";
+            this.label1.Size = new System.Drawing.Size(44, 18);
+            this.label1.TabIndex = 10;
+            this.label1.Text = "详情";
+            // 
             // TestForm
             // 
             this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
-            this.ClientSize = new System.Drawing.Size(1003, 669);
+            this.ClientSize = new System.Drawing.Size(1180, 862);
+            this.Controls.Add(this.groupBox4);
             this.Controls.Add(this.groupBox3);
             this.Controls.Add(this.groupBox2);
             this.Controls.Add(this.groupBox1);
             this.Name = "TestForm";
             this.Text = "TestForm";
+            this.Load += new System.EventHandler(this.TestForm_Load);
             this.groupBox1.ResumeLayout(false);
+            this.groupBox1.PerformLayout();
             this.groupBox2.ResumeLayout(false);
             this.groupBox2.PerformLayout();
             this.groupBox3.ResumeLayout(false);
+            this.groupBox4.ResumeLayout(false);
             this.ResumeLayout(false);
 
         }
@@ -148,5 +197,9 @@ namespace Fine.OPCDaClient9000
         private System.Windows.Forms.TextBox textBox1;
         private System.Windows.Forms.GroupBox groupBox3;
         private System.Windows.Forms.RichTextBox richTextBox1;
+        private System.Windows.Forms.GroupBox groupBox4;
+        private System.Windows.Forms.RichTextBox richTextBox2;
+        private System.Windows.Forms.Label label1;
+        private System.Windows.Forms.RichTextBox richTextBox3;
     }
 }

+ 110 - 1
Fine.OPCDaClient9000/TestForm.cs

@@ -1,10 +1,16 @@
-using Fine.OPCDaClient9000.Util;
+using FaceppSDK;
+using Fine.OPCDaClient9000.Util;
+using Fine.Util;
+using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
+using System.Diagnostics;
 using System.Drawing;
 using System.Linq;
+using System.Net;
+using System.Net.Sockets;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
@@ -64,5 +70,108 @@ namespace Fine.OPCDaClient9000
                 }
             }
         }
+
+        private void TestForm_Load(object sender, EventArgs e)
+        {
+            textBox1.KeyDown += TextBox1_KeyDown;
+            textBox1.KeyPress += TextBox1_KeyPress;
+            
+        }
+
+        private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
+        {
+            Search();
+        }
+
+        private void TextBox1_KeyDown(object sender, KeyEventArgs e)
+        {
+            Search();
+        }
+
+        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
+        {
+            if (listBox1.SelectedItem == null)
+            {
+                MessageBox.Show($"错误:请选择查询结果");
+                return;
+            }
+            var apis = AppUtil.newsConfig.Where(a => a.Data.Exists(b => b.APIName == listBox1.SelectedItem.ToString()));
+            if (apis.Count() > 1)
+            {
+                MessageBox.Show($"错误:文件在以下目录存在相同的配置,请修改:\n{string.Join("\n", apis.Select(a => a.path))}");
+                return;
+            }
+            var api = apis.FirstOrDefault().Data.FirstOrDefault(b => b.APIName == listBox1.SelectedItem.ToString());
+            if (api.Method == "get")
+            {
+                
+                Stopwatch swatch = new Stopwatch();
+                swatch.Start(); //计时开始
+                HttpMethods http = new HttpMethods();
+                var url = $"{GetServerAddress()}{api.APIName}";
+                var result = http.HttpGet(url);
+
+                swatch.Stop(); //计时结束
+                string time = swatch.ElapsedMilliseconds.ToString(); //获取代码段执行时间
+                string showString = DateTime.Now.ToString("yyyy MM dd HH mm ss fff") + $"apiName:{api.APIName};Api方法:{api.Method}\t\n";
+                showString +="总耗时" + time + "\t\n";
+                showString += result + "\t\n";
+                showString+= DateTime.Now.ToString("yyyy MM dd HH mm ss fff") + "\t\n";
+                richTextBox1.Text = showString;
+            }
+            else if (api.Method == "post")
+            {
+                if (string.IsNullOrEmpty(richTextBox2.Text))
+                {
+                    MessageBox.Show("参数为空,请输入参数", "错误信息");
+                    return;
+                }
+                else
+                {
+                    Stopwatch swatch = new Stopwatch();
+                    swatch.Start(); //计时开始
+                    HttpMethods http = new HttpMethods();
+                    var url = $"{GetServerAddress()}{api.APIName}";
+                    var result = http.HttpPost(url,richTextBox2.Text);
+
+                    swatch.Stop(); //计时结束
+                    string time = swatch.ElapsedMilliseconds.ToString(); //获取代码段执行时间
+                    string showString = DateTime.Now.ToString("yyyy MM dd HH mm ss fff") + $"apiName:{api.APIName};Api方法:{api.Method}\t\n";
+                    showString += "总耗时" + time + "\t\n";
+                    showString += result + "\t\n";
+                    showString += DateTime.Now.ToString("yyyy MM dd HH mm ss fff") + "\t\n";
+                    richTextBox1.Text = showString;
+                }
+            }else
+            {
+                MessageBox.Show("接口配置异常,请检查接口","错误信息");
+                return;
+            }
+
+         //   richTextBox1.Text = JsonBeauty.Execute(JsonConvert.SerializeObject(AppUtil.newsConfig.FirstOrDefault(a => a.Data.Exists(b => b.APIName == listBox1.SelectedItem.ToString())).Data.FirstOrDefault(c => c.APIName == listBox1.SelectedItem.ToString()), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
+
+        }
+
+        private string GetServerAddress() {
+           var  httppar = JsonUtil.DeserializeObjectFile<HttpServer.HttpServerParams>("config/httpserver.json");
+           
+            return  $"http://{GetServerIP()}:{httppar.Port}/api/";
+        }
+
+        private string GetServerIP()
+        {
+            string ipstr = "+";
+            var host = Dns.GetHostEntry(Dns.GetHostName());
+            foreach (var ip in host.AddressList)
+            {
+                if (ip.AddressFamily == AddressFamily.InterNetwork)
+                {
+                    ipstr = ip.ToString();
+                    break;
+                }
+
+            }
+            return ipstr;
+        }
     }
 }