最近一個WPF項目須要改寫成android項目,思路是在asp.net項目中編寫一個通用接口,便於其它平臺下調用數據。剛接觸到這些東西的時候徹底是一頭霧水,最根本的緣由是不明白網站中的一個網頁,爲何其它項目就能夠訪問它,並獲取數據。帶着疑問在asp.net項目編寫一個簡單的數據接口,並新建一個小winform項目直接訪問它。本文涉及到的知識點有:在asp.net項目中如何編寫一個數據接口;使用反射辨別響應的方法;以及如何獲取接口的數據。這裏僅僅是介紹如何使用它們,而不講述使用它們的基本原理,一是本人道行淺薄對基本原理不瞭解,懼怕隨便書寫誤導後人;二是若是闡述其基本原理,勢必須要花費大量時間,奈什麼時候間有限。未來若是上述兩個條件知足,必會在最下面作出論述,由於這對本身的進步也是一個確定。閒話少說,開始正文。android
主要內容:json
一、asp.net項目下編寫數據接口服務器
二、使用反射分辨調用方法app
三、新建一個winform項目測試接口的正確性asp.net
一、在asp.net項目下編寫一簡單接口ide
編寫一個方法,構造一個json字符串Response便可。post
private void ExamInfoLogin() { string aa = "8"; string bb = "9"; string roomName = Request.Form["RoomName"]; if (roomName == "806") { aa = "7"; } StringBuilder jsonStringBuilder = new StringBuilder(); jsonStringBuilder.Append("{"); jsonStringBuilder.Append("\"UName\":\"").Append(aa).Append("\","); jsonStringBuilder.Append("\"Password\":\"").Append(bb).Append("\""); jsonStringBuilder.Append("}"); Response.Write(jsonStringBuilder.ToString()); }
二、使用反射選取調用方法測試
假設在aspx頁面中有不少方法,而在使用過程當中每每僅須要調用其中的某一個方法,此處用反射選取調用方法。網站
反射過程當中使用的常量:ui
private const string PAGE_PATH_INFO = "/AppDataInterface/ExamLogin.aspx";//頁面 private const string ASSEMBLY_NAME = "OSCEWEB";//程序集 private const string CLASS_NAME = "OSCEWEB.AppDataInterface.ExamLogin";//類名
重寫OnInit方法:
protected override void OnInit(EventArgs e) { string pathInfo = Request.Params["PATH_INFO"]; if (pathInfo.StartsWith(PAGE_PATH_INFO + "/")) { string[] nameList = pathInfo.Substring(PAGE_PATH_INFO.Length + 1).Split('/'); if (nameList.Length < 1) { Response.End(); return; } try { Assembly assembly = Assembly.Load(ASSEMBLY_NAME); Type type = assembly.GetType(CLASS_NAME); MethodInfo method = type.GetMethod(nameList[0], System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); method.Invoke(this, null); } catch (Exception ex) { Response.End(); return; } } }
在Page_Load方法中添加:
if (Request.Params["PATH_INFO"].StartsWith(PAGE_PATH_INFO + "/")) { Response.End(); }
三、新建一Winform項目,訪問asp.net中數據接口
發佈asp.net項目,網址:http://192.168.4.22:8005
1)無需向數據接口傳遞數據:
private void button1_Click(object sender, EventArgs e) { string strURL = "http://192.168.4.22:8005/AppDataInterface/ExamLogin.aspx/ExamInfoLogin"; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); response = (System .Net.HttpWebResponse )request .GetResponse (); System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = streamReader.ReadToEnd(); streamReader.Close(); MessageBox.Show(responseText); }
獲得的數據是:{"UName":"8","Password":"9"}
2)以post方式向數據接口傳遞數據,獲取接口數據
private void button2_Click(object sender, EventArgs e) { string strURL = "http://192.168.4.22:8005/AppDataInterface/ExamLogin.aspx/ExamInfoLogin"; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; string param = "RoomName=806"; ASCIIEncoding encoding = new ASCIIEncoding (); byte[] data = encoding.GetBytes(param); request.ContentLength = data.Length; System.IO.Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = streamReader.ReadToEnd(); streamReader.Close(); MessageBox.Show(responseText); }
獲得的數據:{"UName":"7","Password":"9"}
、、
string url = System.Configuration.ConfigurationSettings.AppSettings["GetHisOrderUrl"]; string strXml = GetHisOrderXml(hisOrder); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url); request.Method = "POST"; request.ContentType = "text/xml;charset=utf-8"; byte[] data = Encoding.UTF8.GetBytes(strXml); request.ContentLength = data.Length; request.Headers["SOAPAction"] = "http://tempuri.org/IRouterService/RunService"; System.IO.Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse) request.GetResponse(); System.IO.StreamReader streamReader = new System.IO.StreamReader(response .GetResponseStream(),Encoding.UTF8); string responseStr = streamReader.ReadToEnd(); streamReader.Close();
四、總結
按照上述介紹的一些方法確實能完成項目,可是對其爲何該如此仍是充滿疑惑,總感受心中無底、戰戰兢兢,但願有高手能夠對小弟指點一二,不勝感激。
附加:
一、post圖片上傳到服務器中:
public void UploadImage(string imgPath) { var postUrl = string.Empty; HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest; request.AllowAutoRedirect = true; request.Method = "POST"; string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); int pos = imgPath.LastIndexOf("\\"); string fileName = imgPath.Substring(pos + 1); //請求頭部信息 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close(); Stream postStream = request.GetRequestStream(); postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); postStream.Write(bArr, 0, bArr.Length); postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); postStream.Close(); WebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = streamReader.ReadToEnd(); streamReader.Close(); MessageBox.Show(responseText); }
二、