天天看點

Windows Phone 8.1的網絡程式設計之HttpWebRequest類

Windows Phone中有兩個類可以實作HTTP協定的網絡請求:HttpWebRequest類HttpClient類

前者适合處理簡單的網絡請求,後者對HTTP請求的支援更加強大,适合複雜的網絡請求封裝。

不過在此之前需要認識一個HTTP的兩種請求方式:Get請求和Post請求。

兩者的差別是:Get請求:從伺服器上擷取資料,通過URI送出資料,資料在URI中可以看到,同時送出的資料最多隻

能有1024位元組。Post請求:向伺服器傳送資料,通過寫入資料流的方式送出,Post請求對于送出的資料大小沒有限

制。

網絡請求中,肯定會有各種各樣的不确定錯誤,引發WebException,其Status屬性包含訓示錯誤源的

WebExceptionStatus。其枚舉值如下:

Success:成功

ConnectFailure:遠端伺服器連接配接失敗

SendFailure:發送失敗

RequestCanceled:請求被取消

Pending:内部異步請求挂起

UnknownError:未知錯誤

MessageLengthLimitExceeded:網絡請求的消息長度受到限制

示例代碼:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白頁”項模闆在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介紹

namespace App1
{
    /// <summary>
    /// 可用于自身或導航至 Frame 内部的空白頁。
    /// </summary>
    public sealed partial class HttpWebRequestDemo : Page
    {
        public HttpWebRequestDemo()
        {
            this.InitializeComponent();

            //WebRequest和HttpWebRequest
            HttpWebRequest request = HttpWebRequest.CreateHttp("http://www.baidu.com");

            //設定請求的方法
            request.Method = "Get";
            //request.Method = "Post";

            //指定構成HTTP标頭的名稱/值對的集合
            request.Headers["Cookie"] = "stuName = value";
            //設定請求的身份驗證資訊
            request.Credentials = new NetworkCredential("username", "password");
            //發起GetResponse請求,開始對Internet資源的異步請求
            request.BeginGetResponse(responseCallBack, request);
            //request.BeginGetRequestStream(responseStreamCallBack, request);
        }

        //發送擷取發送資料流的請求的響應回調方法
        //private void responseStreamCallBack(IAsyncResult ar)
        //{
        //    HttpWebRequest httpWebRequest = (HttpWebRequest)ar.AsyncState;
        //    using (Stream stream = httpWebRequest.EndGetRequestStream(ar))
        //    {
        //        string content = "testString";
        //        byte[] data = Encoding.UTF8.GetBytes(content);
        //        stream.Write(data, 0, data.Length);
        //    }
        //    httpWebRequest.BeginGetResponse(ResponseCallBackPost, httpWebRequest);
        //}

        //private void ResponseCallBackPost(IAsyncResult ar)
        //{
        //    //和Get請求回調方法一樣
        //}

        //請求回掉方法
        private void responseCallBack(IAsyncResult ar)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)ar.AsyncState;
            WebResponse webResponse = httpWebRequest.EndGetResponse(ar);
            //擷取請求傳回的内容
            using(Stream stream = webResponse.GetResponseStream())
            using(StreamReader sr = new StreamReader(stream))
            {
                //請求傳回的字元串的内容
                string content = sr.ReadToEnd();
            }
        }

        /// <summary>
        /// 在此頁将要在 Frame 中顯示時進行調用。
        /// </summary>
        /// <param name="e">描述如何通路此頁的事件資料。
        /// 此參數通常用于配置頁。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
    }
}
           

繼續閱讀