HttpWebRequest development under. NET Compact Framework

Source: Internet
Author: User
Tags form post

When the Windows Mobile program needs to use Web Server information, WebService will naturally be used in the first place. However, some Web servers do not provide WebService, but only provide Http browsing. To obtain information from an Http webpage, you can use HttpWebRequest and HttpWebResponse. The following is an example.

For example, there is a fuel price query website developed using ASP.net.

Figure 1
Enter the Fuel Type and Postcode to query the Fuel price, as shown in.

Figure 2

In Windows Mobile, You need to develop an application, enter the fuel type and zip code, and then query the price information through the Web Server, which is displayed in Windows Mobile. Because the Web Server does not provide the WebService Service, the Windows Mobile program cannot retrieve the price information directly through Webservice, which can be achieved through HttpWebRequest. For more information about HtppWebRequest, see the following two good articles.
Use HttpWebRequest to submit ASP. NET forms and keep Session and Cookie
HttpWebRequest/Response in a nutshell-Part 1

The overall development involves several steps: Step 1: identify the data to be submitted; Step 2: Access the page and retrieve the ViewState; Step 3: form Post data and send requests; Step 4: Analyze HTML and display results.

Find the data to be submitted

The most common tool for finding the data to be submitted is HttpWatch, but the free basic version of this tool only supports websites such as google and microsoft, so I used a free Firefox plug-in HttpFox, it turns out that this tool meets my needs.
First install HttpFox, and then click "Start" of HttpFox to Start. Open the page to be submitted. For example, http: // localhost/HttpWebRequest/Default. aspx. Click "Search" on the page. View the "Post Data" Tab of HttpFox to find all the Data to be submitted, as shown in figure

The POST to be submitted includes _ VIEWSTATE, _ EVENTVALIDATION, DropDownListFuelType, TextBoxPostCode, and ButtonSearchPostcode.


Figure 3

Retrieve ViewState

The key to ASP.net webform development is to understand the page lifecycle. One of the key points is ViewState. the backend stores the required information in a hidden input box called _ VIEWSTATE, this _ VIEWSTATE will return the Server Control Information (Server controls) to the Server. The following is an example of ViewState.

<Div>
<Input type = "hidden" name = "_ VIEWSTATE" id = "_ VIEWSTATE" value = "/comment + 1 mjzgA ="/>
</Div>
<Div>
<Input type = "hidden" name = "_ EVENTVALIDATION" id = "_ EVENTVALIDATION" value = "/validate"/>
</Div>

 

HttpWebRequest development in CF. NET. If the server is an ASP.net program, ViewState must be processed. As shown in figure 3, in addition to _ VIEWSTATE, the _ EVENTVALIDATION process also needs to be processed. In fact, it is very simple to see which one needs to be obtained through HttpFox.

// Get the ViewState and EventValidation
String URI = "http: // 192.168.1.149/HttpWebRequest/Default. aspx ";
HttpWebRequest request = WebRequest. Create (URI) as HttpWebRequest;
Request. Method = "GET ";
Request. KeepAlive = false;

// Get the response
HttpWebResponse response = request. GetResponse () as HttpWebResponse;
System. IO. Stream responseStream = response. GetResponseStream ();
System. IO. StreamReader reader = new System. IO. StreamReader (responseStream, Encoding. UTF8 );
String srcString = reader. ReadToEnd ();

// Get the ViewState
String viewStateFlag = "id = \" _ VIEWSTATE \ "value = \"";
Int I = srcString. IndexOf (viewStateFlag) + viewStateFlag. Length;
Int j = srcString. IndexOf ("\" ", I );
String viewState = srcString. Substring (I, j-I );

// Get the ViewState
String EventValidationFlag = "id = \" _ EVENTVALIDATION \ "value = \"";
I = srcString. IndexOf (EventValidationFlag) + EventValidationFlag. Length;
J = srcString. IndexOf ("\" ", I );
String eventValidation = srcString. Substring (I, j-I );

 

To retrieve ViewState, you must first access the webpage before submission and use HttpWebRequest request = WebRequest. create (URI) as HttpWebRequest; generate an HttpWebRequest object. The parameter is the address of the Web server and the submission method is "GET". In fact, this method can also be seen through HttpFox, for example:

Figure 4
Start HttpFox first, and then enter the URL. The first line shows that this is a "GET" operation.
HttpWebResponse response = request. GetResponse () as HttpWebResponse; send a request to the Web server and get the returned information. The returned information is actually the "Content" Tab in figure 4, that is, the HTML information, which contains the ViewState we need.

Form Post data and send requests

After processing the result, we can get _ VIEWSTATE and _ EVENTVALIDATION. Then we can make up the submitted operation and the Post data, as shown in the following code:

// Compose the URL
ViewState = Uri. EscapeDataString (viewState );
EventValidation = Uri. EscapeDataString (eventValidation );

String formatString = "_ VIEWSTATE = {0} & __ EVENTVALIDATION = {1} & DropDownListFuelType = {2} & TextBoxPostCode = {3} & ButtonSearchPostcode = Search ";
String postString = string. Format (formatString, viewState, eventValidation, fuelType, postCode );

// Change to byte []
Byte [] postData = Encoding. ASCII. GetBytes (postString );

// Compose the new request
Request = WebRequest. Create (URI) as HttpWebRequest;
Request. Method = "POST ";
Request. KeepAlive = false;
Request. ContentType = "application/x-www-form-urlencoded ";
Request. ContentLength = postData. Length;

System. IO. Stream outputStream = request. GetRequestStream ();
OutputStream. Write (postData, 0, postData. Length );
OutputStream. Close ();

// Get the new response
Response = request. GetResponse () as HttpWebResponse;
ResponseStream = response. GetResponseStream ();
Reader = new System. IO. StreamReader (responseStream );
SrcString = reader. ReadToEnd ();
Return srcString;

 

The Post data must be formatted using Uri. EscapeDataString. If the submitted data contains Chinese characters, perform this operation. Otherwise, an error occurs.

String formatString = "_ VIEWSTATE = {0} & __ EVENTVALIDATION = {1} & DropDownListFuelType = {2} & TextBoxPostCode = {3} & ButtonSearchPostcode = Search ";
String postString = string. Format (formatString, viewState, eventValidation, fuelType, postCode );

It is the memory that makes up the Post. All the content comes from the analysis of HttpFox. See figure 3. What is the composition.
Then, use HttpWebRequest and HttpWebResponse to submit the request. The returned result contains the price information we need.

Analyze HTML and Display Results

After the result is obtained, You need to analyze HTML and display the required information. In this example, you can use simple string analysis to obtain the price information from LabelResult.

Int I = srcString. IndexOf ("Price = [");
Int j = srcString. IndexOf ("</span> ");
LabelPrice. Text = srcString. Substring (I, j-I );

 
Here is just a simple example. In actual use, you can use regular expression for analysis, or use an HTML analyzer for explanation.

A simple HttpWebRequest application has been described so far. For the source code, see the following. To run this code, you need to modify the IP address. Here, the address of the Server is hardcode.
If you use Emulator for testing, you can refer to creating a network connection in Windows Mobile Emulator.

Source code: HttpWebRequestTester.rar

 

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.