Problem
How to send a simple http get request and retrieve the corresponding HTTP response.
Design
Create a WebClient class instance and use its downloaddata () method.
Solution
String Uri = " Http: // server/path/webform. aspx " ; WebClient WC = New WebClient (); console. writeline ( " Sending an http get request " + Uri ); Byte [] Bresponse = WC. downloaddata (URI ); String Strresponse = Encoding. ASCII. getstring (bresponse); console. writeline ( " HTTP response is: " ); Console. writeline (strresponse );
Annotation
The WebClient class is part of the system. Net life namespace. By default, it is accessible to console programs. Through WebClient. downloaddata () method to retrieve an HTTP response is extremely simple, but downloaddata () returns only a byte array (byte array), which must be passed through system. text. encoding. ASCII. the getstring () method converts it into a string. Another solution is to use the WebClient. openread () method and associate it with a stream:
String Uri = " Http: // server/path/webform. aspx " ; WebClient WC = New WebClient (); console. writeline ( " Sending an http get request " + Uri); stream St = WC. openread (URI); streamreader SR = New Streamreader (ST ); String Res = Sr. readtoend (); Sr. Close (); ST. Close (); console. writeline ( " HTTP response is " ); Console. writeline (RES );
Compared with ASP. NET web applications, The WebClient class is more suitable for testing static HTML web pages. This code can be used to detect the responses returned by the ASP. NET program, but to expand this code into an automatic testing program, you need to check the HTTP response as expected. Section 5.8 uses the technology in this section. In section 5.8, we use programming methods to determine the viewstate value of ASP. NET web applications. The technologies involved in section 5.11 demonstrate how to check an HTTP response based on the given expectations.