手动发送HTTP请求调用和异步调用网络服务

  

<强>

(1),得到方式调用:

字符串strURL=" http://localhost: 12074/Service1.asmx/GetProductPrice ? ProductId=";
  strURL +=this.textBox1.Text;//创建一个HTTP请求
  HttpWebRequest请求=(HttpWebRequest) WebRequest.Create (strURL);//得到请求方式
  request.Method=盎竦谩?//获得响应流
  HttpWebResponse响应=(System.Net.HttpWebResponse) request.GetResponse ();
  流s=response.GetResponseStream ();
  XmlTextReader读者=new XmlTextReader(年代);
  Reader.MoveToContent ();
  字符串strValue=https://www.yisu.com/zixun/Reader.ReadInnerXml ();
  strValue=https://www.yisu.com/zixun/strValue.Replace (“, lt;”、“& lt;”);
  strValue=https://www.yisu.com/zixun/strValue.Replace(“和gt;”、“在”);
  MessageBox.Show (strValue);
  Reader.Close (); 

(2),发布方式调用:

字符串strURL=" http://localhost: 12074/Service1.asmx GetProductPrice”;//创建一个HTTP请求
  HttpWebRequest请求=(HttpWebRequest) WebRequest.Create (strURL);//后请求方式
  请求。方法=癙OST”;//内容类型
  请求。ContentType="应用程序/x-www-form-urlencoded”;//参数经过URL编码
  字符串paraUrlCoded=HttpUtility.UrlEncode (“ProductId”);
  paraUrlCoded +="=" + HttpUtility.UrlEncode (this.textBox1.Text);
  byte[]有效载荷;//将URL编码后的字符串转化为字节
  有效载荷=System.Text.Encoding.UTF8.GetBytes (paraUrlCoded);//设置请求的ContentLength
  请求。ContentLength=payload.Length;//获得请求流
  流作家=request.GetRequestStream ();//将请求参数写入流
  作家。写(有效载荷,0,payload.Length);//关闭请求流
  writer.Close ();//获得响应流
  HttpWebResponse响应=(HttpWebResponse) request.GetResponse ();
  流s=response.GetResponseStream ();
  XmlTextReader读者=new XmlTextReader(年代);
  Reader.MoveToContent ();
  字符串strValue=https://www.yisu.com/zixun/Reader.ReadInnerXml ();
  strValue=https://www.yisu.com/zixun/strValue.Replace (“, lt;”、“& lt;”);
  strValue=https://www.yisu.com/zixun/strValue.Replace(“和gt;”、“在”);
  MessageBox.Show (strValue);
  Reader.Close (); 

<强>

(1),利用Backgroundworker对象实现。

///& lt; summary>///界面的进度条显示///& lt;/summary>
  空白ChangeProcessBar ()
  {
  for (int i=0;我& lt;10;我+ +)
  {
  progressBar1。值=https://www.yisu.com/zixun/i;
  System.Threading.Thread.Sleep (500);
  }
  }
  私人空间button1_Click(对象发送方,EventArgs e)
  {
  BackgroundWorker BackgroundWorker=new BackgroundWorker ();//注册具体异步处理的方法
  backgroundworker。DoWork +=new DoWorkEventHandler (back_DoWork);//注册调用完成后的回调方法
  backgroundworker。新RunWorkerCompletedEventHandler RunWorkerCompleted +=(back_RunWorkerCompleted);//这里开始异步调用
  backgroundworker.RunWorkerAsync ();//调用服务的同时客户端处理并不停止
  ChangeProcessBar ();
  }//完成事件
  空白back_RunWorkerCompleted(对象发送方,RunWorkerCompletedEventArgs e)
  {
  如果(e。错误!=null)
  把e.Error;
  progressBar1。值=progressBar1.Maximum;//调用完成了,把客户端进度条填充满
  字符串价格=e.Result.ToString ();//获取处理结果
  对话框。显示(“调用完成。价格是:”+价格);//显示从服务器获取的结果值
  }//调用方法
  空白back_DoWork(对象发送方,DoWorkEventArgs e)
  {//Web服务代理类
  ProductService。LTPService服务=new ProductService.LTPService ();//调用Web方法GetProductPrice,结果赋值给DoWorkEventArgs的结果对象
  e。结果=service.GetProductPrice (“001”);
  }

(2),利用WebService的webMethod中的异步方法实现。

手动发送HTTP请求调用和异步调用网络服务