zoukankan      html  css  js  c++  java
  • Receive HTTP Post via ASP.Net Generic Handler(服务端与客户端定时通讯机制)

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

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

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

    [csharp]

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

    然后我们写一个简单的客户端来测试它。在这个客户端里我们实现了一个类HttpClient来进行HTTP POST操作:

    [csharp]

    1. // -----------------------------------------------------------------------
    2. // Http protocol client.
    3. // -----------------------------------------------------------------------
    4. namespace ConsoleClient
    5. {
    6. using System;
    7. using System.IO;
    8. using System.Net;
    9. using System.Text;
    10. /// <summary>
    11. /// Http protocol client.
    12. /// </summary>
    13. public class HttpClient
    14. {
    15. /// <summary>
    16. /// Post data to specific url and get response content.
    17. /// </summary>
    18. /// <param name="url">the url to post</param>
    19. /// <param name="postData">post data</param>
    20. /// <returns>response content</returns>
    21. public string Post(string url, string postData)
    22. {
    23. Uri uri = new Uri(url);
    24. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    25. request.Method = "POST";
    26. request.ContentType = "application/x-www-form-urlencoded";
    27. Encoding encoding = Encoding.UTF8;
    28. byte[] bytes = encoding.GetBytes(postData);
    29. request.ContentLength = bytes.Length;
    30. using (Stream writer = request.GetRequestStream())
    31. {
    32. writer.Write(bytes, 0, bytes.Length);
    33. writer.Close();
    34. }
    35. return this.ReadResponse(request);;
    36. }
    37. /// <summary>
    38. /// Read response content from http request result.
    39. /// </summary>
    40. /// <param name="request">http request object</param>
    41. /// <returns>response content.</returns>
    42. private string ReadResponse(HttpWebRequest request)
    43. {
    44. string result = string.Empty;
    45. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    46. {
    47. using (Stream responseStream = response.GetResponseStream())
    48. {
    49. using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
    50. {
    51. result = reader.ReadToEnd();
    52. reader.Close();
    53. }
    54. }
    55. }
    56. return result;
    57. }
    58. }
    59. }
    // -----------------------------------------------------------------------
    // Http protocol client.
    // -----------------------------------------------------------------------
    
    namespace ConsoleClient
    {
        using System;
        using System.IO;
        using System.Net;
        using System.Text;
    
        /// <summary>
        /// Http protocol client.
        /// </summary>
        public class HttpClient
        {
            /// <summary>
            /// Post data to specific url and get response content.
            /// </summary>
            /// <param name="url">the url to post</param>
            /// <param name="postData">post data</param>
            /// <returns>response content</returns>
            public string Post(string url, string postData)
            {
                Uri uri = new Uri(url);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
    
                Encoding encoding = Encoding.UTF8;
                byte[] bytes = encoding.GetBytes(postData);
    
                request.ContentLength = bytes.Length;
    
                using (Stream writer = request.GetRequestStream())
                {
                    writer.Write(bytes, 0, bytes.Length);
                    writer.Close();
                }
    
                return this.ReadResponse(request);;
            }
    
            /// <summary>
            /// Read response content from http request result.
            /// </summary>
            /// <param name="request">http request object</param>
            /// <returns>response content.</returns>
            private string ReadResponse(HttpWebRequest request)
            {
                string result = string.Empty;
    
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            result = reader.ReadToEnd();
                            reader.Close();
                        }
                    }
                }
    
                return result;
            }
        }
    }
    
    
    

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

    [csharp]

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

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

  • 相关阅读:
    iOS- storyboard this class is not key value coding-compliant for the key xxx
    iOS-iOS 获取蓝色文件夹图片
    新浪微博客户端(45)-显示表情
    新浪微博客户端(44)-分页表情键盘
    iOS-设置UIPageControl 显示图片
    codeforces736D. Permutations(线性代数)
    POJ2505 A multiplication game(博弈)
    BZOJ3073: [Pa2011]Journeys(线段树优化建图 Dijkstra)
    SPOJ KATHTHI
    洛谷P2827 蚯蚓(单调队列)
  • 原文地址:https://www.cnblogs.com/jx270/p/2687892.html
Copyright © 2011-2022 走看看