標籤:style blog http color 使用 os
public string szJson = ""; byte[] json; UploadClass up = new UploadClass(); public ValidatePage() { InitializeComponent(); } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { //我做了一個實現上傳某些關鍵的Json資料,返回伺服器Appid的功能,類似新浪微博擷取AccessToken,不過微博SDK已經封裝好了上傳功能,比我這個簡單許多。 GetAppid(); } void GetAppid() { up.device = "Luma1020"; up.devid = "abcdefghijklmn123456"; up.os = "8.0"; up.appid = "987654321asdfghjkl"; DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(UploadClass)); //序列化要發送的資訊 using (MemoryStream ms = new MemoryStream()) { dc.WriteObject(ms, up); //報錯的原因是UploadClass的類名沒有寫public json = ms.ToArray(); ms.Close(); //一定要關閉流 szJson = Encoding.UTF8.GetString(json, 0, json.Length); //伺服器要求用UTF8,就在代碼中轉換成UTF8,要求用別的就轉換成相應的格式。 } //從這一步開始,準備向伺服器發送資料。 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.xxxx.com/Api/xxxxx"); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = json.Length; IAsyncResult result = (IAsyncResult)request.BeginGetRequestStream(GetRequestCallback, request); } private void GetRequestCallback(IAsyncResult asyncResult) { HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; using (Stream sm = request.EndGetRequestStream(asyncResult)) { sm.Write(json, 0, json.Length); } request.BeginGetResponse(GetResponseCallback, request); } void GetResponseCallback(IAsyncResult result) { Stream stream = null; UploadClass uc = null; //new 一個供返回Json資料的執行個體 HttpWebRequest req = (HttpWebRequest)result.AsyncState; WebResponse webresponse = req.EndGetResponse(result); stream = webresponse.GetResponseStream(); using (StreamReader reader = new StreamReader(stream)) { string contents = reader.ReadToEnd(); uc = new UploadClass(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(contents.ToString()))) { DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(UploadClass)); uc = (UploadClass)ds.ReadObject(ms); } } //這種回呼函數中不能直接在函數體裡寫UI的語句,需要用Dispatcher去通知UI改變。 if (uc.code == "0") { Dispatcher.BeginInvoke (() => { //這些都是前台UI,下面都是例子: IDTextBlock.Text = "AppId: " + up.id; DeviceTextBlock.Text = "Device: " + up.device; } ); } else { Dispatcher.BeginInvoke(() => { //和上面一樣,根據自己的UI自行設定。 }); } }
我在做這個模組時也參考了許多網上的例子,不過和大多數人的通病一樣,就是他能正常運行,我就不能運行,因此我也排除了各種BUG,比如上面注釋裡寫道的一些細節。
在標題裡我把幾個關鍵詞也寫上了,便於朋友們搜尋,希望這篇部落格能協助你們!