Windows 运行时中支持网络资源访问的对象:HttpWebRequest 对象
发送 GET/POST 请求,HttpHelper 封装,超时控制。
HttpClient 对象
发送 GET/POST 请求,请求进度监控。
两种常用请求方式:GET 请求
主要是从服务器请求数据
可以传递有限(1024字节)数据
POST 请求
主要是往服务器发送数据,传递数据大小没有限制。
也可以接收服务端数据,但大多数是请求结果标识。
HttpWebRequest
<Grid>
<WebView
x:Name="webView"/>
</Grid>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
//创建请求对象
HttpWebRequest request = WebRequest.CreateHttp("http://www.baidu.com");
//设置请求参数
request.Accept = "*/*";
request.Method = "GET";
request.Headers["Cookie"] = "key1=value;key2=val";//密码存储区
//发送请求,获取服务端响应
var response = await request.GetResponseAsync();
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var result = await reader.ReadToEndAsync();
webView.NavigateToString(result);
}
}
}
Index
<StackPanel>
<TextBox x:Name="txt1"/>
<TextBox x:Name="txt2"/>
<TextBox x:Name="txt3"/>
<Button
Content="Send"
Click="Button_Click"/>
</StackPanel>
private async void Button_Click(object sender, RoutedEventArgs e)
{
//建立WebRequest对象
var request = HttpWebRequest.Create("http://localhost:7080/index.ashx");
//设置Method类型为GET/POST
request.Method = "POST";
//设置请求Cookie
request.Headers["Cookie"] = "cookie_key1=CookieValue1;cookie_key2=CookieValue2";
//设置请求UserAgent为常用Chrome代理
request.Headers["User-Agent"] = "Mozilla/5.0(Windows NT 6.3;Win64;x64)AppleWebKit/537.36(KHTML,like Gecko)Chrome/41.0.2243.0 safari/537.36";
//设置请求身份验证网络凭据,用于网络身份验证
//request.Credentials = new NetworkCredential("111", "2222");
var bs = Encoding.UTF8.GetBytes("123:321");
request.Headers["Authorization"] = string.Format("Basic{0}", Convert.ToBase64String(bs, , bs.Length)); //设置请求提交格式
request.ContentType = "application/x-www-form-urlencode";
//待发送的数据 格式与QueryString格式相同
var sendString = string.Format("txt1={0}&txt2={1}&txt3=(2)", txt1.Text, txt2.Text, txt3.Text);
//转换成字节数组用于发送
var buffer = Encoding.UTF8.GetBytes(sendString);
//设置发送请求流
using (var stream = await request.GetRequestStreamAsync())
{
//写到请求体中
stream.Write(buffer, , buffer.Length);
} //发送请求,获取服务端响应
var response = await request.GetResponseAsync();
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var result = await reader.ReadToEndAsync();
}
}
}