Example: Receive HTTP Post via ASP.Net Generic Handler 转

假设我们要提供一个小小的服务,采用HTTP协议进行通讯,客户端 POST 一些数据到服务器上。客户端不一定是PC,更不一定会按照一个Web Form的格式来提交数据,它可能是一个运行在PC上的Desktop Application,也可能是一个移动设备。

 

服务器端接收这样的请求极其简单,下面寥寥数行代码即可实现:

在Web站点中新建一个Generic Handler(*.ashx),代码如下:

  1. <%@ WebHandler Language= "C#"  Class= "Echo"  %>  
  2.   
  3. using  System;  
  4. using  System.Web;  
  5. using  System.IO;  
  6.   
  7. public   class  Echo : IHttpHandler  
  8. {  
  9.     private  System.Text.Encoding DefaultEncoding = System.Text.Encoding.UTF8;  
  10.       
  11.     public   void  ProcessRequest (HttpContext context)  
  12.     {  
  13.         context.Response.ContentType = "text/plain" ;  
  14.         context.Response.ContentEncoding = DefaultEncoding;  
  15.   
  16.         Stream inputStream = context.Request.InputStream;  
  17.         using  (StreamReader reader =  new  StreamReader(inputStream, DefaultEncoding))  
  18.         {  
  19.             string  requestContent = reader.ReadToEnd();  
  20.             string  responseContent =  string .Format( "Received: {0} <== END" , requestContent);  
  21.               
  22.             context.Response.Write(responseContent);  
  23.         }  
  24.     }  
  25.   
  26.     public   bool  IsReusable  
  27.     {  
  28.         get  {  return   false ; }  
  29.     }  
  30. }  

然后我们写一个简单的客户端来测试它。在这个客户端里我们实现了一个类HttpClient来进行HTTP POST操作:
  1. // -----------------------------------------------------------------------   
  2. // <copyright file="HttpClient.cs" author="Yaping Xin">   
  3. // Http protocol client.   
  4. // </copyright>   
  5. // -----------------------------------------------------------------------   
  6.   
  7. namespace  ConsoleClient  
  8. {  
  9.     using  System;  
  10.     using  System.IO;  
  11.     using  System.Net;  
  12.     using  System.Text;  
  13.   
  14.     /// <summary>   
  15.     /// Http protocol client.   
  16.     /// </summary>   
  17.     public   class  HttpClient  
  18.     {  
  19.         /// <summary>   
  20.         /// Post data to specific url and get response content.   
  21.         /// </summary>   
  22.         /// <param name="url">the url to post</param>   
  23.         /// <param name="postData">post data</param>   
  24.         /// <returns>response content</returns>   
  25.         public   string  Post( string  url,  string  postData)  
  26.         {  
  27.             Uri uri = new  Uri(url);  
  28.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);  
  29.             request.Method = "POST" ;  
  30.             request.ContentType = "application/x-www-form-urlencoded" ;  
  31.   
  32.             Encoding encoding = Encoding.UTF8;  
  33.             byte [] bytes = encoding.GetBytes(postData);  
  34.   
  35.             request.ContentLength = bytes.Length;  
  36.   
  37.             using  (Stream writer = request.GetRequestStream())  
  38.             {  
  39.                 writer.Write(bytes, 0, bytes.Length);  
  40.                 writer.Close();  
  41.             }  
  42.   
  43.             return   this .ReadResponse(request);;  
  44.         }  
  45.   
  46.         /// <summary>   
  47.         /// Read response content from http request result.   
  48.         /// </summary>   
  49.         /// <param name="request">http request object</param>   
  50.         /// <returns>response content.</returns>   
  51.         private   string  ReadResponse(HttpWebRequest request)  
  52.         {  
  53.             string  result =  string .Empty;  
  54.   
  55.             using  (HttpWebResponse response = (HttpWebResponse)request.GetResponse())  
  56.             {  
  57.                 using  (Stream responseStream = response.GetResponseStream())  
  58.                 {  
  59.                     using  (StreamReader reader =  new  StreamReader(responseStream, Encoding.UTF8))  
  60.                     {  
  61.                         result = reader.ReadToEnd();  
  62.                         reader.Close();  
  63.                     }  
  64.                 }  
  65.             }  
  66.   
  67.             return  result;  
  68.         }  
  69.     }  
  70. }  

然后我们这样就能得到HTTP POST的返回:

  1. // Replace the string content with your actual address please.   
  2. string  defaultUrl =  "http://ServerName:8081/WebPath/AnyService.ashx" ;  
  3.   
  4. HttpClient client = new  HttpClient();  
  5. string  response = client.Post(defaultUrl, @ "abc 123! 测试 @" );  
  6.   
  7. Console.OutputEncoding = System.Text.Encoding.UTF8;  
  8. Console.WriteLine(response);  


假设Client与Server两端都约定好采取某个格式对数据进行序列化与反序列化,例如都采用Json,客户端把对象通过Json封装后 Post给Server,Server再采用Json将对象从Json字符串中解析出来,这样进行数据传递是便利的。再假设我们要压缩传送出的数据量,那 么可以进行gzip压缩与解压。又假设我们要考虑安全性,那么我们可以在对象的结构中添加security token进行认证,以及采用某种加密算法对字符串进行加密与解密。怎么发挥就看您具体的应用了,构建一个属于您自己的轻量的service易如反掌。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值