您的位置:首页 > 理论基础 > 计算机网络

Windows Phone 十六、HttpClient

2015-06-25 02:53 609 查看
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;");

<Grid>
<TextBox x:Name="txtUrl"/>
<Button Content="DOWN" Click="Button_Click"/>
</Grid>


protected async override void OnNavigatedTo(NavigationEventArgs e)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", "111:222");
//GET请求
var result = await client.GetStringAsync(new Uri("http://localhost:7080/index.ashx"));

var dict = new Dictionary<string, string>();
dict.Add("ke1", "val1");
dict.Add("ke2", "val2");
//await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpFormUrlEncodedContent(dict));
//await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpStringContent("abc"));

var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync("1.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.AppendTextAsync(file, "abcdefghijklmnopqrstuvwxyz");
var fileStream = await file.OpenAsync(FileAccessMode.Read);
await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpStreamContent(fileStream));
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
//定义请求Uri
var requestUri = new Uri(txtUrl.Text);
//创建一个Http请求客户端HttpClient
var client = new HttpClient();
//创建定期监视对象
IProgress<HttpProgress> progress = new Progress<HttpProgress>((p) =>
{
//此处参数P,可以获取到进度相关信息
System.Diagnostics.Debug.WriteLine(p.BytesReceived + "/" + p.TotalBytesToReceive);
});
//在异步任务中加入进度监控
HttpResponseMessage response = await client.GetAsync(requestUri).AsTask(progress);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: