Differences between Windows Phone 7-WebClient and HttpWebRequest

Source: Internet
Author: User

This article will first introduce the use of HttpWebRequest and the differences between the two categories and the impact on WP7.

Before discussing WebClient and HttpWebRequest, you must first understand a very important category: WebRequest category.

‧ WebRequest

It is the main model of. NET Framework for processing Web request and response. Belongs to the Abstract category. There is no way to use the WebRequest. Create method to Create an object directly by constructing a sub-implementation. This category also has other categories related to communication protocols, including WebRequestMethod. File, WebRequestMethod. Ftp, and WebRequestMethod. Http. For more details, see


However, in the release E. in the Netm namespace, only the following types are supported: WebRequest, WebResponse, WebClient, and HttpWebRequest. Although WebRequestMethod is missing. does Ftp or FtpWebRequest mean that Silverlight cannot support FTP? The answer is no. Because WebClient can achieve the same effect (but pay attention to the Timeout problem), because WebClient is a very useful post-encapsulation class, this makes it easy for our developers to write programs that retrieve network resources. In addition, you can refer to the following article: Silverlight 3 File Transfer Application.


Then we will go back to the topic and talk about the two categories related to the WebClient and HttpWebRequest under Silverlight that are commonly used in Silverlight.

‧ WebClient

WebClient uses the WebRequest class to provide access to resources. Compared with the HttpWebRequest type, the WebClient category is more like a category encapsulated to access network resources. For example, when using WebClient according to the preset value, this executor does not transmit selective Http headers, that is, the Uris you use will generate the corresponding Http Header content, so that the receiver can effectively retrieve the required content. This allows developers to complete tasks based on the Basic headers. However, the use of headers is still restricted. For more information, see

<WebHeaderCollection type> this article introduces the headers that can be operated to communicate with the acceptor.

Method

Description

OpenWriteAysnc

The Stream used to transmit data to resources in non-synchronous mode, without blocking the call execution thread. Use the POST command to upload HTTP resources. This method transfers data to the data stream for transmission.

UploadStringAsync

Transmits the String to the resource without blocking the call execution thread. The specified upload URI must identify the resources that can accept the POST method transfer requirements.

DownloadStringAsync

Download the String from the resource without blocking the call execution thread. Use the GET method to download the specified resource from the URI.

OpenReadAsync

Data is returned from the resource in non-synchronous mode without blocking the call execution thread. The download encapsulation method is used to ensure that the resource is returned as an independent file set. Use the GET method to download the specified resource from the URI.

The top four methods are commonly used in non-synchronous jobs. However, when using the WebClient category, pay attention to the network access restrictions of Silverlight. For more information, see <network security access restrictions in Silverlight> and <URL access restrictions in Silverlight>. In addition, you may not know why there is a DownloadStringAsync or UploadStringAsync method like I do, because the WebClient category examples are found on the Internet using the other two types: openWriteAsync and OpenReadAsync are used to store network resources. You may use the following categories as needed:

> DownloadStringAsync/UploadStringAsync: Applicable to the types of data transmitted at the receiving end, such as XML and JSON.

> OpenWriteAsync/OpenReadAsync: Applicable to the types of data streams received/obtained by the receiving end in POST mode. For example, the data type that can be converted to Stream.


HttpWebRequest

It is the descendant category of WebRequest. It implements the methods and Attributes provided by WebRequest, and mainly processes Http protocols. It includes headers and Content, which are generally stored in ASP.. NET page. Allows users to communicate directly with the Http server, such as Get or Post. This method is similar to the WebRequest class usage: WebRequest. Create returns the HttpWebRequest object based on http or https In the URI.

However, when using HttpWebRequest, note: "The Silverlight execution stage restricts the transfer of the HttpWebReuqest category from a specific Header to a cross-domain website." This restriction mainly prevents cross-domain access by programs, events that cause cross-domain attacks can also ensure that resources are accessed under security and standards. For more information about security, see <network security access restrictions in Silverlight> and <URL access restrictions in Silverlight>.


The main Method used:

Method Name

Description

BeginGetResponse

Starts non-synchronous requirements on Internet resources.

EndGetResponse

End non-synchronization requirements for Internet resources. IAsyncResult must be used to process the returned results.

BeginGetRequestStream

Non-synchronous requirements for Stream objects used to write data.

EndGetRequestStream

End non-synchronization requirements for Stream objects used to write data. IAsyncResult must be used to process the returned results.

The above two groups of Methods correspond to Request/Response (In addition, GetResponse () and other methods supporting synchronization jobs ). Both of them are non-synchronous calls, so there are two important categories to note:

> AsyncCallback Delegation

Allows client applications to complete non-synchronous jobs. When starting a non-synchronous job, the user-End call-back delegate is provided. The event processing frequency referenced by AysncCallback includes the workflow logic for processing non-synchronous jobs. However, the returned results are controlled by the IAsyncResult interface.


> IAsyncResult Interface

Implemented by the category of the non-synchronous job method. Return Type, which indicates the start and end of a non-synchronous job ). When a non-synchronous job is completed, the information is sent back to the AsyncCallback delegate called invoke.


The following is a simple example:

I implemented a web page of Default. aspx and received the action of sending the User's account and password to the web page through the GET Method for verification. (The example is a bit bad, but the focus is on how to use the HttpWebRequest category ).

Private void button#click (object sender, RoutedEventArgs e)

{

// Create an HttpWebReuqest object

HttpWebRequest tHReuqest = WebRequest. CreateHttp ("http: // localhost: 1294/Default. aspx? UID = pou & PWD = pou1234 ");

// Use AsyncCallback to delegate tasks to non-synchronous tasks.

THReuqest. BeginGetResponse (new AsyncCallback (ResponseCallback), tHReuqest );

}

Private void ResponseCallback (IAsyncResult asynchronousResult)

{

// Use AsyncCallback to delegate a task that requires implementing the IAsyncResult interface to obtain the status of a non-synchronous job.

HttpWebRequest tRequest = (HttpWebRequest) asynchronousResult. AsyncState;

HttpWebResponse tResponse = (HttpWebResponse) tRequest. EndGetResponse (asynchronousResult );

Using (StreamReader tResponseStream = new StreamReader (tResponse. GetResponseStream ()))

{

String strResult = tResponseStream. ReadToEnd ();

// After reading the Response content, call the UI Thread to modify the display of the elements in the screen.

Dispatcher. BeginInvoke () =>

{

TextBox1.Text = strResult;

});

}

}

‧ Differences between WebClient and HttpWebRequest

WebClient and HttpWebReuqest have never been clear about how to use this type when I first learned Silverlight. Maybe you have referred to this article <Using WebClient and HttpWebRequest>, it also mentions the use of the two categories. If it is used in a simple situation (for example, retrieve the content or file returned by the specified URI through GET ), the difference between the two is relatively small, which is easy to cause confusion. However, after describing their respective purposes and functions, you can easily break down the differences between the two through the following section:


> WebClient: it is easy to use and can be used directly to retrieve or download resources and content on the Web Service, or even support FTP.

> HttpWebRequest: it is complicated to use, but it provides rich functions to customize the required headers or other resources to assist in specific work.


Indeed, in the use of WebClient, you don't have to worry too much about the control and application of parameters on the Http Header. Compared with HttpWebReqeust, it is very simple to use (However, this does not mean that WebClient cannot adjust the required Header content. You can adjust the required Header Through the Header attribute of WebClient.).

The above is just a simple classification. We can refer to the following content for actual use situations and considerations:


<HTTP communication and security using Silverlight> I will extract some of the important parts to help you understand the differences between the two when learning Silverlight.


> HTTP Communication scenarios and Suggestions

The following table describes the "HTTP Communication scenarios and recommended practices" in <HTTP communication and security using Silverlight>:

Serial number

Plot

Recommended Methods

1

Download and upload resources in the same domain.

Use the WebClient category. For more information, see download as needed.

2

Call an HTTP architecture Web Service loaded on the same domain.

Use the WebClient category or HttpWebRequest/HttpWebResponse category. For more information, see how to: HTTP-based service delivery requirements [SilverLT4].

3

Call a SOAP, WCF, or ASP. net ajax Web Service loaded on the same domain.

Call the Proxy generated by the Web service. For more information, see use Proxy to build and access the service [Silverlight].

If you do not want to use Proxy, use the HttpWebRequest/HttpWebResponse category.

4

Process XML, JSON, or RSS data from Web Services.

Use the WebClient category or HttpWebRequest/HttpWebResponse category. For more information, see directly accessing HTTP and REST-based services [SilverLT4] or how to: Use LINQ to xml to load XML files from any URI location.

5

Call a Web service on a different domain.

Determine whether the client access principle is in the domain root directory. Use the Proxy, WebClient category, or HttpWebRequest/HttpWebResponse category. For more information, see [SilverLT4].

6

Send PUT, DELETE, and other HTTP methods, including custom methods.

Determine the client access principle to enable other HTTP methods. Specify the HTTP processing on the user end and use the HttpWebRequest/HttpWebResponse type in general mode. For details about HTTP processing on the user end, see how to: specify a browser or HTTP processing on the user end.

7

Set request headers for cross-domain POST requirements.

Determine whether the header is allowed according to the user-side access principle.

Use the WebClient category for required headers for data uploading. Set its Headers attribute to the required header set.

For other cases, use the HttpWebRequest type. Set its Headers attribute to the required header set. For a list of allowed Headers, see HttpWebRequest. Headers.

8

Use all methods to send request headers.

Specify the HTTP processing on the client, use the HttpWebRequest/HttpWebResponse type in the general way, and set the Headers attribute as needed.

9

Send requests to the SOAP service that returns error codes and SOAP errors

Specify the client for HTTP processing and use the HttpWebRequest/HttpWebResponse type in the general method to retrieve the message body that has an error. For details about HTTP processing on the user end, see how to: specify a browser or HTTP processing on the user end.

10

Send the GET request to the Web service that requires the Referer header.

Specify the HTTP processing on the user end and use the HttpWebRequest/HttpWebResponse type in general mode. For details about HTTP processing on the user end, see how to: specify a browser or HTTP processing on the user end.

The situations mentioned in the above table are common in the use of WebClient or HttpWebRequest. However, you can find the situations in numbers 1, 2, 4, and 7, the situations used by the WebClient are simple, such as uploading, downloading, or common Header title applications. In addition, the situation provided by HttpWebReqeust includes a wide range of customized Http Header applications, specified Web Service, WCF, or specific Http Method Applications. The preceding table only provides an approximate application mode. In fact, only the applicable methods and content can be found based on the situations encountered during development.


In addition, it is important to note that Silverlight defines and corresponds to cross-domain restrictions (important: When Silverlight accesses different domains, A "user-side access principle file/cross-domain principle file" is required for another domain to identify whether the Service supports cross-domain applications based on the specifications defined in the principle ). In addition, the following articles define principles and security definitions: <enable services to use [SilverLT4] Across domain boundaries> and <other security considerations for service access [SilverLT4]>.


The above is a small experience in self-organizing and reading WebClient and HttpWebRequest, because the use of the two is not very in-depth, you can only provide some simple Induction Based on the current reading results. Hope to help. Thank you. If any error occurs, please provide more instructions. Thank you.

 

 

Http://www.hugwp.com/thread-2736-1.html

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.