[Windows Phone 8開發]使用HttpWebRequest和HttpWebResponse向伺服器發送Json資料(POST方法)

來源:互聯網
上載者:User

標籤: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,比如上面注釋裡寫道的一些細節。

 

在標題裡我把幾個關鍵詞也寫上了,便於朋友們搜尋,希望這篇部落格能協助你們!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.