Receive http post via ASP. NET generic handler (timed communication between the server and the client)

Source: Internet
Author: User

Suppose we want to provide a small service that uses the HTTP protocol for communication, and the client post some data to the server. The client may not be a PC, but may not submit data in a web form format. It may be a desktop application running on a PC or a mobile device.

It is extremely simple for the server to receive such a request.CodeYou can achieve:

Create a new generic handler (*. ashx) on the web site. The Code is as follows:

[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 ;}}}

Then we write a simple client to test it. In this client, we implement the httpclient class to perform the http post operation:

[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 leleclient {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. 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 ;}}}

Then we can get the http post response:

[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! Test @");
    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 (defaurl URL, @ "abc 123! Test @ "); console. outputencoding = system. Text. encoding. utf8; console. writeline (response );

assume that both the client and server agree to adopt a certain format for data serialization and deserialization. For example, both clients adopt JSON, and the client encapsulates the object through JSON and then post it to the server, the server then parses the object from the JSON string using JSON, which facilitates data transmission. If we want to compress the data volume, we can perform gzip compression and decompression. If we want to consider security, we can add security tokens in the object structure for authentication, and uses some encryption algorithm to encrypt and decrypt strings. How to use it depends on your specific application. It is easy to build a lightweight service of your own.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.