How to implement C WinForm request http

Yisu cloud 2022-06-23 18:12:26 阅读数:940


C# winform request http How to achieve

This article mainly explains “C# winform request http How to achieve ”, Interested friends might as well come and have a look . The method introduced in this paper is simple and fast , Practical . Now let Xiaobian take you to learn “C# winform request http How to achieve ” Well !

    One :.Net There are two classes in HttpWebRequest and HttpWebResponse Class to achieve Http Request

    Implementation steps :

    1. adopt WebRequest Class to create a HttpWebRequest The object of , This object can contain Http Request information .
    2. Set up HttpWebRequest object , In fact, it's setting up Http Information content of the request message .
    3. from HttpWebRequest Get in object HttpWebResponse object , The object contains Http Response information .
    4. Get the response header information and response subject information from the response information .

    Two : HTTP Defines and The server Different ways of interacting

    The basic method is GET,POST,PUT,DELETE, Check the , The , increase , Delete . In general, we only use GET and POST,

    POST And GET The difference of

    1.GET Get data from the server ,POST Is to send data to the server .
    2.GET The parameter data queue is added to the submission form ACTION Attribute refers to URL in , Value corresponds to each field in the form one by one , stay URL Can be seen in .POST It's through HTTPPOST Mechanism , Place the fields and their contents in the HTML HEADER Transfer to ACTION Attribute refers to URL Address . Users don't see the process .
    3. about GET The way , Server side Request.QueryString Get the value of the variable , about POST The way , Server side Request.Form Get submitted data .
    4.GET Small amount of data transmitted , Not greater than 2KB( This is mainly due to URL Length limit ).POST Large amount of data transmitted , It is generally defaulted to unlimited . But in theory, , Limitations depend on the processing power of the server .
    5.GET Low security ,POST High security . because GET During transmission , Data is placed on the requested URL in , Today, there are many servers 、 Either the proxy server or the user agent will request URL Log to a log file , And put it somewhere , In this way, some private information may be seen by a third party . in addition , Users can also see the submitted data directly on the browser , Some system internal messages will be displayed in front of users .POST All operations of are invisible to the user .

    Two simple Get Request and Post request

    1.Get request

    string strURL = "http://localhost/WinformSubmit.php?tel=11111&name= Zhang San ";System.Net.HttpWebRequest request;//  Create a HTTP request request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);//request.Method="get";System.Net.HttpWebResponse response;response = (System.Net.HttpWebResponse)request.GetResponse();System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);string responseText = myreader.ReadToEnd();myreader.Close();MessageBox.Show(responseText);

    2.Post request

    string strURL = "http://localhost/WinformSubmit.php";System.Net.HttpWebRequest request;request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);//Post Request mode request.Method = "POST";//  Content type request.ContentType = "application/x-www-form-urlencoded";//  Parameters go through URL code string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword");paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(" Many months ");byte[] payload;// take URL The encoded string is converted to bytes payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);// Set the requested  ContentLength request.ContentLength = payload.Length;// Please   Seeking flow System.IO.Stream writer = request.GetRequestStream();// Write request parameters to the stream writer.Write(payload, 0, payload.Length);//  Close the request stream writer.Close();System.Net.HttpWebResponse response;//  Get response flow response = (System.Net.HttpWebResponse)request.GetResponse();System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);string responseText = myreader.ReadToEnd();myreader.Close();MessageBox.Show(responseText);

    A little test

    Request Baidu home page ( ) The content of , That is to get Baidu home page html Content .

    establish HttpWebRequest request , Set request message information

     // request string uri =;HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;request.Method = "GET";                            // Request method request.ProtocolVersion = new Version(1, 1);   //Http/1.1 edition //Add Other ...

    Receiving response , Output response header information and subject information

    HttpWebResponse response=request.GetResponse() as HttpWebResponse;   //Header   foreach (var item in response.Headers)     {     this.txt_Header.Text += item.ToString()+": " +        response.GetResponseHeader  (item.ToString())     + System.Environment.NewLine;  }     // If the subject information is not empty , Then the subject information content is received    if (response.ContentLength <= 0)      return;   // Receive response subject information    using(Stream stream =response.GetResponseStream())   {     int totalLength=(int)response.ContentLength;     int numBytesRead=0;     byte[] bytes=new byte[totalLength+1024];    // Read the data in the stream through a loop , Finished reading , Out of the loop      while( numBytesRead < totalLength  )     {      int num=stream.Read(bytes,numBytesRead,1024);  // Every time you want to read 1024 byte       if( num==0 )   // This indicates that the data in the stream has been read         break;      numBytesRead+=num;     }   }   // Display the received entity data on the interface    string content=Encoding.UTF8.GetString(bytes);   this.txt_Content.Text=content;

    Here we are , I'm sure you're right “C# winform request http How to achieve ” Have a deeper understanding of , You might as well put it into practice ! This is the Yisu cloud website , For more relevant contents, you can enter the relevant channels for inquiry , Pay attention to our , Continue to learn !

    版权声明:本文为[Yisu cloud]所创,转载请带上原文链接,感谢。