標籤:
HttpClient 對象也可以實現網路請求
相對於 HttpWebRequest 對象來說,HttpClient 操作更簡單,功能更強大
HttpClient 提供一系列比較簡單的API來實現基本的請求
同時也支援身分識別驗證和非同步作業
注意 Windows Runtime 平台中有兩個 HttpClient 類型,調用方式幾乎相同,以下內容使用 Windows.Web.Http 中的 HttpClient
發送資料格式
HttpFormUrlEncodedContent
HttpMultipartContent
HttpMultipartFormDataContent
HttpBufferContent
HttpStreamContent
HttpStringContent
設定 Cookie:client.DefaultRequestHeaders.Add("Cookie", "cookie_key1=CookieValue1; cookie_key2=CookieValue2;");
1 <Grid>2 <TextBox x:Name="txtUrl"/>3 <Button Content="DOWN" Click="Button_Click"/>4 </Grid>
1 protected async override void OnNavigatedTo(NavigationEventArgs e) 2 { 3 HttpClient client = new HttpClient(); 4 client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", "111:222"); 5 //GET請求 6 var result = await client.GetStringAsync(new Uri("http://localhost:7080/index.ashx")); 7 8 var dict = new Dictionary<string, string>(); 9 dict.Add("ke1", "val1");10 dict.Add("ke2", "val2");11 //await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpFormUrlEncodedContent(dict));12 //await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpStringContent("abc"));13 14 var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync("1.txt", CreationCollisionOption.ReplaceExisting);15 await FileIO.AppendTextAsync(file, "abcdefghijklmnopqrstuvwxyz");16 var fileStream = await file.OpenAsync(FileAccessMode.Read);17 await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpStreamContent(fileStream));18 }19 20 private async void Button_Click(object sender, RoutedEventArgs e)21 {22 //定義請求Uri23 var requestUri = new Uri(txtUrl.Text);24 //建立一個Http請求用戶端HttpClient25 var client = new HttpClient();26 //建立定期監視對象27 IProgress<HttpProgress> progress = new Progress<HttpProgress>((p) =>28 {29 //此處參數P,可以擷取到進度相關資訊30 System.Diagnostics.Debug.WriteLine(p.BytesReceived + "/" + p.TotalBytesToReceive);31 });32 //在非同步任務中加入進度監控33 HttpResponseMessage response = await client.GetAsync(requestUri).AsTask(progress);34 }
Windows Phone 十六、HttpClient