WebRequst的使用

WebClient和HttpWebRequst是用来获取数据的2种方式,在我的这篇数据访问(2)中主要是讲的WebClient的使用,一般而言,WebClient更倾向于“按需下载”,事实上掌握它也是相对容易的,而HttpWebRequst则允许你设置请求头或者对内容需要更多的控制,后者有点类似于form中的submit。虽然两者都是异步请求事件,但是WebClient是基于事件的异步,而HttpWebRequst是基于代理的异步编程,下面就用简单的需求两者比较用法上的不同:

需求很简单,获取Web端的图片然后显示出来,结构如右边所示

  UI很简单:
 <StackPanel Background="White">
            <Button Width="250"
                    Content="HttpWebRequest"
                    Click="Button_Click" />
            <Button Width="250"
                    Content="Click for request with WebClient"
                    Click="Button_Click_1" />
            <TextBox  Text="1"
                      x:Name="numTextBox"
                      Width="20" />
            <Image Height="150"
                   Name="image1"
                   Stretch="Fill"
                   Width="200" />
        </StackPanel>

页面上提供一个TextBox用来输入文件名的,先看一看WebClient获取图片并显示在Image的过程

       //使用WebClient
        private 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如果要实现相同的代码的过程

       //使用WebRequest
        private 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 stream=response.GetResponseStream();
  BitmapImage bitmap = new BitmapImage();
  bitmap.SetSource(stream);
  this.image1.Source = bitmap;

WebClient与WebRequest差异的更多相关文章

  1. 第三节:总结.Net下后端的几种请求方式(WebClient、WebRequest、HttpClient)

    一. 前言 前端调用有Form表单提交,ajax提交,ajax一般是用Jquery的简化写法,在这里不再过多介绍: 后端调用大约有这些:WebCient.WebRequest.Httpclient.W ...

  2. Csharp:WebClient and WebRequest use http download file

    //Csharp:WebClient and WebRequest use http download file //20140318 塗聚文收錄 string filePath = "20 ...

  3. c#利用WebClient和WebRequest获取网页源代码的比较

    前几天举例分析了用asp+xmlhttp获取网页源代码的方法,但c#中一般是可以利用WebClient类和WebRequest类获取网页源代码.下面分别说明这两种方法的实现. WebClient类获取 ...

  4. C#、.NET网络请求总结(WebClient和WebRequest)

    1.关于WebClient第三方的封装,支持多文件上传等 using System; using System.Collections.Generic; using System.Text; usin ...

  5. c#利用WebClient和WebRequest获取网页源代码

    C#中一般是可以利用WebClient类和WebRequest类获取网页源代码.下面分别说明这两种方法的实现.   WebClient类获取网页源代码   WebClient类   WebClient ...

  6. 淘宝开放平台使用WebClient,WebRequest访问时的错误提示导致麻烦

    淘宝开放平台(TOP)提供OAuth2.0支持 通过C#的WebClient/WebRequest直接访问时会提示grant type is empty,这是一个非常恼人的错误,你会发现即使传了这个参 ...

  7. WebClient和WebRequest获取html代码

    HTML: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.as ...

  8. C# WebClient,HttpClient,WebRequest

    static void WebClientDemo() { string url = "https://www.cnblogs.com/Fred1987/p/11843418.html&qu ...

  9. 反射:修改请求头HttpWebRequest/Webclient Header属性的date值-"此标头必须使用适当的属性进行修改"

    场景:调用外部接口,接口要求Header信息里面包涵Date信息,且Date信息必须是格式化好的,(他们用的是Java),但是C#默认的是Date属性不能被修改, 所以就会出现下面的错误: 未处理的异 ...

随机推荐

  1. Effective STL(第7条)

    第7条:如果容器中包含了通过new操作创建的指针,切忌在容器对象析构前将指针delete掉 //向一个vector中添加多个new出来的对象 void doSomething(){ vector< ...

  2. 无法在提交表单前通过ajax验证解决办法

    博主在一个小项目中,要实现注册表单无刷新验证用户名或密码,但是发现不管怎么样都无法在先通过ajax验证之前不提交表单. 例如:一个简单的验证函数 function check(){ $.post(&q ...

  3. poj1700

    这题的最坑的地方就是每步可能会有两种情况,这两情况起初我都单独考虑了,但就是没放在一起考虑...wa个不停,果然贪心是一个很考验思维的东西. 这里可以这样考虑,在运人的过程中,河的起始岸最后终将剩下一 ...

  4. AspxSpy2014 Final

    受bin牛委托修改并发布,版权归bin牛所有. Bug/建议提交:zcgonvh@rootkit.net.cn 祝各位马年大吉,财源滚滚. 免责声明: 本程序只用于管理员安全检测,使用前请注意环境与法 ...

  5. Spring 定时器

    <!-- 对定时任务进行引用 --> <bean id="schedulerFactory" class="org.springframework.sc ...

  6. 使用engine关键字指定该表使用哪个engine

    建表及插入数据语句:mysql> create table salary(userid int,salary decimal(9,2));Query OK, 0 rows affected (0 ...

  7. 一次与iptables有关的Openstack排错

    先说下环境: 宿主机A(192.168.1.242)上运行着实例a(192.168.1.176), 宿主机B(192.168.1.56)上运行着实例b(192.168.1.50). 用户说从实例b上t ...

  8. 【iCore3 双核心板】例程六:IWDG看门狗实验——复位ARM

    实验指导书及代码包下载: http://pan.baidu.com/s/1c0frjHm iCore3 购买链接: https://item.taobao.com/item.htm?id=524229 ...

  9. what's the difference between dim as and dim as new?

    what's the difference between dim as and dim as new? There is no difference with value types (Intege ...

  10. springmvc Failed to load resource: the server responded with a status of 404 (Not Found)

    jsp页面导入css.js提示上述问题. Spring对静态资源的请求做专门处理 <!-- 对静态资源的请求 --><mvc:resources location="/js ...