1. 程式人生 > >C# Winform 客戶端架構 呼叫 REST 傳輸 Json

C# Winform 客戶端架構 呼叫 REST 傳輸 Json

【架構】

1. 定義 GET、POST、PUT、DELETE,標準REST基礎。

2. 為了相容多終端,日期、時間格式統一為Int,定義時間轉換工具類。(Java 與 C# getTime起算日不同,Java為1970年起)

3. Http圖片,載入到記憶體,顯示。工具類。

4. 反射 根據實體類動態生成 DataGridView 資料,提供複用性,減少程式設計師工作。

【JAVA服務端程式碼跳轉】點選開啟連結

【效果】以此圖效果為案例,描述架構過程

【DataGridView 資料動態生成】

1. 獲取搜尋條件,組裝URL

2. HttpClientUtil作為REST客戶端,呼叫GET方法,返回JSON字串

3. JSON字串,根據泛型,轉換成實體

4. 根據實體,反射遍歷實體所有屬性,動態生成DataTable

5. DataGridView 繫結 dataTable

private void listDataGridView()
        {
            string naturalId = this.txtNaturalId.Text;
            string barcode = this.txtBarcode.Text;
            string url = "/stocks/commoditystocks/" + "inPage/?pageNumber=1&pageSize=10&orderBy=&filter=naturalId_S_" + naturalId + "_LIKE__,barcode_S_" + barcode + "_LIKE__,qty_I_0_GT__&";
            List<CommodityStocks> commodityStockList = HttpClientUtil.doGetMethodToObj<List<CommodityStocks>>(url);
            DataTable dataTable = HttpClientUtil.toDataTable(commodityStockList);
            this.dataGridView1.DataSource = dataTable;
        }

【HttpClientUtil 核心】

1. 定義 GET、POST、PUT、DELETE,標準REST基礎

2. 定義 Json 序列化,反序列化 私有方法

3. 定義 根據實體,反射遍歷實體所有屬性,動態生成DataTable

namespace WindowsFormsApplication1.xiazhi.common
{
    public class HttpClientUtil
    {

        private static string xiazhi_tomcat_url = Properties.Settings.Default.xiazhi_server_url;
        private static string xiazhi_server_url = xiazhi_tomcat_url + "resteasy";

        // REST @GET 方法,根據泛型自動轉換成實體,支援List<T>
        public static T doGetMethodToObj<T>(string metodUrl)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xiazhi_server_url + metodUrl);
            request.Method = "get";
            request.ContentType = "application/json;charset=UTF-8";
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                MessageBox.Show(e.Message + " - " + getRestErrorMessage(response));
                return default(T);
            }
            string json = getResponseString(response);
            return JsonConvert.DeserializeObject<T>(json);
        }

        // 將 HttpWebResponse 返回結果轉換成 string
        private static string getResponseString(HttpWebResponse response)
        {
            string json = null;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
            {
                json = reader.ReadToEnd();
            }
            return json;
        }

        // 獲取異常資訊
        private static string getRestErrorMessage(HttpWebResponse errorResponse)
        {
            string errorhtml = getResponseString(errorResponse);
            string errorkey = "spi.UnhandledException:";
            errorhtml = errorhtml.Substring(errorhtml.IndexOf(errorkey) + errorkey.Length);
            errorhtml = errorhtml.Substring(0, errorhtml.IndexOf("\n"));
            return errorhtml;
        }

        // REST @POST 方法
        public static T doPostMethodToObj<T>(string metodUrl, string jsonBody)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xiazhi_server_url + metodUrl);
            request.Method = "post";
            request.ContentType = "application/json;charset=UTF-8";
            var stream = request.GetRequestStream();
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(jsonBody);
                writer.Flush();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string json = getResponseString(response);
            return JsonConvert.DeserializeObject<T>(json);
        }

        // REST @PUT 方法
        public static string doPutMethod(string metodUrl)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xiazhi_server_url + metodUrl);
            request.Method = "put";
            request.ContentType = "application/json;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
            {
                return reader.ReadToEnd();
            }
        }

        // REST @PUT 方法,帶傳送內容主體
        public static T doPutMethodToObj<T>(string metodUrl, string jsonBody)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xiazhi_server_url + metodUrl);
            request.Method = "put";
            request.ContentType = "application/json;charset=UTF-8";
            var stream = request.GetRequestStream();
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(jsonBody);
                writer.Flush();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string json = getResponseString(response);
            return JsonConvert.DeserializeObject<T>(json);
        }

        // REST @DELETE 方法
        public static bool doDeleteMethod(string metodUrl)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xiazhi_server_url + metodUrl);
            request.Method = "delete";
            request.ContentType = "application/json;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
            {
                string responseString = reader.ReadToEnd();
                if (responseString.Equals("1"))
                {
                    return true;
                }
                return false;
            }
        }

        //根據實體,反射遍歷實體所有屬性,動態生成DataTable
        public static DataTable toDataTable(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                FieldInfo[] fieldInfos = list[0].GetType().GetFields();
                foreach (FieldInfo fi in fieldInfos)
                {
                    if (fi.Name.Length > 4 && fi.Name.LastIndexOf("Date") == fi.Name.Length - 4)
                    {
                        result.Columns.Add(fi.Name, "".GetType());
                        continue;
                    }
                    if (fi.Name.Length > 4 && fi.Name.LastIndexOf("Time") == fi.Name.Length - 4)
                    {
                        result.Columns.Add(fi.Name, "".GetType());
                        continue;
                    }
                    if (fi.Name.IndexOf("imagepath") >= 0)
                    {
                        result.Columns.Add(fi.Name, Image.FromFile("1.jpg").GetType());
                        continue;
                    }
                    result.Columns.Add(fi.Name, fi.FieldType);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (FieldInfo fi in fieldInfos)
                    {
                        object obj = fi.GetValue(list[i]);
                        if (null == obj)
                        {
                            tempList.Add(obj);
                            continue;
                        }
                        if (fi.Name.Length > 4 && fi.Name.LastIndexOf("Date") == fi.Name.Length - 4)
                        {
                            int dateInt = (int)obj;
                            if (0 == dateInt)
                            {
                                tempList.Add("");
                                continue;
                            }
                            obj = DateTimeUtil.convertIntDatetime(dateInt).ToShortDateString();
                        }
                        if (fi.Name.Length > 4 && fi.Name.LastIndexOf("Time") == fi.Name.Length - 4)
                        {
                            int dateInt = int.Parse(obj.ToString());
                            if (0 == dateInt)
                            {
                                tempList.Add("");
                                continue;
                            }
                            obj = DateTimeUtil.convertIntDatetime(dateInt).ToString();
                        }
                        if (fi.Name.IndexOf("imagepath") >= 0)
                        {
                            if (null == obj)
                            {
                                tempList.Add("");
                                continue;
                            }
                            WebClient myWebClient = new WebClient();
                            MemoryStream ms = new MemoryStream(myWebClient.DownloadData(xiazhi_tomcat_url + obj.ToString()));
                            obj = Image.FromStream(ms);
                        }
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }

    }
}


【Java -- C# 時間轉換】

namespace WindowsFormsApplication1.xiazhi.common.util
{
    public class DateTimeUtil
    {
        public static int convertDateTimeInt(DateTime time)
        {
            int intResult = 0;
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = int.Parse((time - startTime).TotalSeconds.ToString().Substring(0, 10));
            return intResult;
        }

        public static DateTime convertIntDatetime(int utc)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            startTime = startTime.AddSeconds(utc);
            return startTime;
        }

        public static DateTime getMonthFirstDay()
        {
            int year = DateTime.Now.Year;
            int month = DateTime.Now.Month;
            DateTime firstDayOfThisMonth = new DateTime(year, month, 1);
            return firstDayOfThisMonth;
        }
    }
}