淮安网站建设设计制作,在网站上做教育直播平台多少钱,客户资源管理系统,广州响应式网站WebRequst的使用 WebClient和HttpWebRequst是用来获取数据的2种方式#xff0c;在我的这篇数据访问(2)中主要是讲的WebClient的使用#xff0c;一般而言#xff0c;WebClient更倾向于“按需下载”#xff0c;事实上掌握它也是相对容易的#xff0c;而HttpWebRequst则允许你…WebRequst的使用 WebClient和HttpWebRequst是用来获取数据的2种方式在我的这篇数据访问(2)中主要是讲的WebClient的使用一般而言WebClient更倾向于“按需下载”事实上掌握它也是相对容易的而HttpWebRequst则允许你设置请求头或者对内容需要更多的控制后者有点类似于form中的submit。虽然两者都是异步请求事件但是WebClient是基于事件的异步而HttpWebRequst是基于代理的异步编程下面就用简单的需求两者比较用法上的不同 需求很简单获取Web端的图片然后显示出来结构如右边所示 UI很简单 StackPanel BackgroundWhiteButton Width250ContentHttpWebRequestClickButton_Click /Button Width250ContentClick for request with WebClientClickButton_Click_1 /TextBox Text1x:NamenumTextBoxWidth20 /Image Height150Nameimage1StretchFillWidth200 //StackPanel 页面上提供一个TextBox用来输入文件名的先看一看WebClient获取图片并显示在Image的过程 //使用WebClientprivate void Button_Click_1(object sender, RoutedEventArgs e){string baseUri String.Format(http://localhost:49280/Images/{0}.jpg, this.numTextBox.Text.Trim());Uri uri new Uri(baseUri, UriKind.Absolute);WebClient client new WebClient();client.OpenReadCompleted new OpenReadCompletedEventHandler(client_OpenReadCompleted);}void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e){ Stream stream e.Result;BitmapImage bitmap new BitmapImage();bitmap.SetSource(stream);this.image1.Source bitmap;} 因为之前已经对WebClient总结过了所以就不再重复了主要是看一看WebRequst如果要实现相同的代码的过程 //使用WebRequestprivate void Button_Click(object sender, RoutedEventArgs e){string baseUri String.Format(http://localhost:49280/Images/{0}.jpg,this.numTextBox.Text.Trim());HttpWebRequest request (HttpWebRequest) WebRequest.Create(baseUri);request.Method GET;request.BeginGetResponse(new AsyncCallback(ReadCallback), request);}public void ReadCallback(IAsyncResult asyc){HttpWebRequest request (HttpWebRequest)asyc.AsyncState; HttpWebResponse response (HttpWebResponse)request.EndGetResponse(asyc); this.Dispatcher.BeginInvoke(() {Stream stream response.GetResponseStream();BitmapImage bitmap new BitmapImage();bitmap.SetSource(stream);this.image1.Source bitmap;});} 几点需要注意的地方: 1,HttpWebRequest是个抽象类所以无法new的需要调用HttpWebRequest.Create(); 2,其Method指定了请求类型这里用的GET,还有POST也可以指定ConentType; 3,其请求的Uri必须是绝对地址; 4,其请求是异步回调方式的从BeginGetResponse开始并通过AsyncCallback指定回调方法 5,因为其回调不是UI线程所以不能直接对UI进行操作这里使用Dispatcher.BeginInvoke() 主要是第4点如果把上面的代码中回调方法改成这样下面的样子的话VS会提示跨域线程访问无效 HttpWebRequest request (HttpWebRequest)asyc.AsyncState;HttpWebResponse response (HttpWebResponse)request.EndGetResponse(asyc); Stream streamresponse.GetResponseStream();BitmapImage bitmap new BitmapImage();bitmap.SetSource(stream);this.image1.Source bitmap;转载于:https://www.cnblogs.com/626498301/archive/2010/08/13/1798662.html