Chapter 5. Building an HTTP Client

In this chapter, you will learn how to:

  • View the HTTP message structure that is required to communicate with an XML Web service.

  • Build a client application that consumes an XML Web service using the HTTP-GET and HTTP-POST protocols.

At the beginning of Chapter 4, we mentioned the three protocols you can use to invoke the functionality of an XML Web service: SOAP, HTTP-GET, and HTTP-POST. Chapter 4 focused on the development of clients that use SOAP and proxy classes. In this chapter, we will focus on the direct use of the HTTP-GET and HTTP-POST protocols to develop similar client functionality.

HTTP-GET and HTTP-POST Protocols

Hypertext Transfer Protocol (HTTP) is the standard transport for communicating with XML Web services even when using SOAP; HTTP encapsulates the SOAP message as it travels across the network. When we discuss the use of the HTTP-GET and HTTP-POST protocols in the context of consuming XML Web services, we are referring to the ability to invoke XML Web service methods by using HTTP alone, without the use of SOAP.

In the context of HTTP, GET and POST are not protocols at all; they are two of several different methods (or commands) that can be used for interacting with Web servers. However, the ability to pass arguments and data as part of the HTTP-GET and HTTP-POST methods makes them a simple and suitable mechanism for invoking an XML Web service. The simplicity of the HTTP approach carries limitations that we highlight later, in the section "Comparing HTTP and SOAP."

The service help pages automatically generated by ASP.NET include an example of how to use the HTTP-GET protocol to invoke XML Web service methods. We used this mechanism in the section "Testing the VISAValidator XML Web Service" in Chapter 3.

Comparing HTTP-GET and HTTP-POST

The key difference between the HTTP-GET and HTTP-POST methods is how data is carried in the request message. HTTP-GET requests append data to the URL; a question mark signals the end of the address and the start of the data. Each data element appears as a name/value pair; semi-colons separate multiple data elements. HTTP-POST requests contain data in the body of the HTTP request. Again, data elements are name/value pairs, but each data element occupies a separate line of the request body. You can see the differences between HTTP-GET and HTTP-POST message structures on the service help pages for an XML Web service.

Procedure 5-1. Compare the HTTP-GET and HTTP-POST message structures

  1. Start Internet Explorer.

  2. In the Address text field, enter the URL of the .asmx file for the VISAValidator XML Web service that we created in Chapter 3. The URL for this service is http://localhost/XMLWebServices/Chapter03/VisaValidator/Validation.asmx.

    Compare the HTTP-GET and HTTP-POST message structures
  3. Click the ValidateVISACard link to display the help page for that operation.

  4. Scroll down the Web page, past the Test and SOAP sections, until you see the HTTP GET section. You will see the structure of the HTTP-GET request required to invoke the ValidateVISACard method, followed by a sample HTTP response.

    Compare the HTTP-GET and HTTP-POST message structures
  5. Scroll down further, and you will see the HTTP POST section. This section includes both the equivalent HTTP-POST message for invoking the ValidateVISACard method and a sample HTTP response.

    Compare the HTTP-GET and HTTP-POST message structures
  6. Look at the sample responses in both the HTTP GET and HTTP POST sections. You will notice that they are the same for both protocols. Regardless of whether you use HTTP-GET or HTTP-POST, the XML Web service returns the same XML fragment.

    Compare the HTTP-GET and HTTP-POST message structures

Comparing HTTP and SOAP

HTTP-GET and HTTP-POST provide a simple mechanism for consuming XML Web services that offers some benefits over the use of SOAP.

  • Correctly structured HTTP-GET and HTTP-POST messages are easy to generate, which is particularly useful in the development of lightweight and legacy clients that cannot use SOAP. Even a simple HTML form is sufficient, as demonstrated by the invocation capabilities provided by the ASP.NET service help pages.

  • Responses to HTTP-GET and HTTP-POST messages do not require complex XML processing. The response contains XML, but it has a simple structure and can easily be processed using normal string manipulation techniques. This makes HTTP-GET and HTTP-POST useful for platforms that do not have XML support, including legacy systems and, again, lightweight clients.

  • HTTP-GET and HTTP-POST messages are simpler than SOAP messages. The complexity of constructing types from complex XML documents is not required, which can result in improved performance.

However, when compared to SOAP, the HTTP-GET and HTTP-POST protocols have some important limitations that hamper their usefulness in all but the simplest of XML Web services.

  • You cannot use the HTTP protocols to invoke XML Web service methods that take complex data types as arguments. We discuss complex data types in Chapter 6.

  • You can invoke XML Web service methods that return complex types, but the response will simply contain name/value pairs for each field contained in the complex type; the returned data has no structure. You must extract the data manually by referring to the information in the WSDL file for the XML Web service.

  • You cannot pass arguments by reference using the HTTP protocols. We discuss by reference arguments in Chapter 6.

  • Using the HTTP protocols to communicate with an XML Web service is not an agreed-to industry standard technique. Although the HTTP protocols will work with XML Web services developed as ASP.NET Web applications, they may not work with services developed with other mechanisms or running on other platforms.

Consuming XML Web Services Using HTTP

Even when using the simpler HTTP protocols to consume XML Web services, you have a lot of flexibility in how to implement the communications. Primarily, you must choose between implementing the HTTP handling directly or by using a proxy class.

HTTP Proxy Classes

We discussed the use of proxy classes to access XML Web services in Chapter 4, focusing on them from the perspective of abstracting the complexity of SOAP. You can also use proxy classes to communicate with XML Web services using the HTTP-GET or HTTP-POST protocols.

When you create a Web reference in Visual Studio .NET, the generated proxy class will always use SOAP if an XML Web service supports SOAP. This ensures that the proxy exposes the maximum functionality of the XML Web service, avoiding the inherent limitations of the HTTP protocols. If the service does not support SOAP, the proxy class will use HTTP-GET. Finally, if the service does not support HTTP-GET, HTTP-POST is used.

Note

The Wsdl.exe tool that comes with the .NET Framework SDK provides greater control over the generation of proxy classes. Wsdl.exe allows you to specify which protocol to use. We discuss the Wsdl tool in Chapter 16.

We will not discuss the use of proxy classes that communicate by using the HTTP protocols in much detail in this chapter. They are used in the same manner as SOAP proxies, discussed in Chapter 4. We will proceed to describe the direct use of HTTP-GET and HTTP-POST to consume XML Web service functionality.

Creating a Web Forms Client

We will create a Web Forms application with an interface that’s the same as in the WebFormsClient project we created in Chapter 4. However, instead of using a proxy class and SOAP, we will manipulate the HTTP-GET protocol directly to invoke the ValidateVISACard method of the VISAValidator XML Web service. We could have elected to generate a Windows Forms client or a console application, but for this simple example, the ability to copy the Web Forms project from Chapter 4 will save you some time.

The approach we take in this example is straightforward. When the user clicks the Validate button, we formulate a URL that contains the address of the ValidateVISACard method of the VISAValidator service and append the argument (the VISA card number) to the URL as data. We base the URL structure on what’s shown on the service help page that we discussed earlier, in the section "Comparing HTTP-GET and HTTP-POST."

We also take a simple approach to the HTTP manipulation, using a StringBuilder object to construct the HTTP-GET request, a WebClient to send the request and receive the response, and simple string comparison to determine the result. The .NET Framework class library provides other (more functional) classes that you could use, but we felt it best to use simple classes with which most developers will have experience.

Important

More than anything, this example highlights the benefits of using proxy classes to communicate with XML Web services. Even for such a simple example, the HTTP manipulation can be confusing. Also, if the service were to change, this tight coupling could result in extensive code changes.

Procedure 5-2. Copy the WebFormsClient Application

  1. Use the process we described in the section "Copying Web Projects" earlier in this chapter to make a copy the WebFormsClient project you developed in Chapter 4. Copy the project to the URL http://localhost/XMLWebServices/Chapter05/WebFormsClient .

  2. Close the old project, open the new one, and save the new solution file before proceeding.

  3. In Solution Explorer, right-click the WebForm1.aspx file and select Set As Start Page from the shortcut menu. This step is required so that Visual Studio .NET knows which file to load when we test the application later.

Procedure 5-3. Modify the WebFormsClient Application

  1. In Solution Explorer, double-click on the WebForm1.aspx entry. WebForm1 opens in design view.

    Modify the WebFormsClient Application
  2. In the WebForm1 design view, double-click on the Validate button.

    Visual Studio .NET opens the code view for WebForm1 and displays the ValidateButton_Click method, which executes when the user clicks the Validate button.

  3. Replace the existing ValidateButton_Click method with the following code.

    Example 5-1. C#

    private void ValidateButton_Click(object sender, 
        System.EventArgs e) {
        // create the request URL
        StringBuilder x_builder = new StringBuilder();
        // add the host element of the URL
        x_builder.Append("http://localhost");
        // add the first part of the URL of the Web Service
        x_builder.Append("/XMLWebServices/Chapter03/");
        // add the second part of the URL of the Web Service
        x_builder.Append("VisaValidator/Validation.asmx");
        // add the details of the method we want to invoke
        x_builder.Append("/ValidateVISACard?");
        // add the argument name and the value we want to
        // supply for the argument
        x_builder.Append("p_card_number=" +
            CreditCardNumberText.Text);
        // create the web client and obtain the response data
        // as a byte array
        WebClient x_web_client = new WebClient();
        byte[] x_response =
            x_web_client.DownloadData(x_builder.ToString());
        // process the string result to obtain a validation result
        bool x_valid =
            processResultString(
                Encoding.Default.GetString(x_response));
        if (x_valid) {
            ResultLabel.Text = "Number Valid";
        } else {
            ResultLabel.Text = "Number Invalid";
        }
    }

    Example 5-2. Visual Basic .NET

    Private Sub ValidateButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles ValidateButton.Click
        ‘ create the request URL
        Dim x_builder As StringBuilder = New StringBuilder()
        ‘ add the host element of the URL
        x_builder.Append("http://localhost")
        ‘ add the first part of the URL of the Web Service
        x_builder.Append("/XMLWebServices/Chapter03/")
        ‘ add the second part of the URL of the Web Service
        x_builder.Append("VisaValidator/Validation.asmx")
        ‘ add the details of the method we want to invoke
        x_builder.Append("/ValidateVISACard?")
        ‘ add the argument name and the value we want to
        ‘ supply for the argument
        x_builder.Append("p_card_number=" + CreditCardNumberText.Text)
        ‘ create the web client and obtain the response data
        ‘ as a byte array
        Dim x_web_client As WebClient = New WebClient()
        Dim x_response() As Byte = _
            x_web_client.DownloadData(x_builder.ToString())
        ‘ process the string result to obtain a validation result
        Dim x_valid As Boolean = _
            processResultString(Encoding.Default.GetString(x_response))
        If x_valid Then
            ResultLabel.Text = "Number Valid"
        Else
            ResultLabel.Text = "Number Invalid"
        End If
    End Sub
  4. Add the following processResultString method as a member of the WebForm1 class.

    This method performs a simple test on the XML returned from the ValidateVISACard Web method. If the string >true</boolean> is found within the XML document, we deduce that the VISA card is valid and return true; otherwise we return false. This is not a robust approach to handling the result, but it is sufficient for the purpose of our demonstration.

    Example 5-3. C#

    private bool processResultString(string p_result) {
        if (p_result.IndexOf(">true</boolean>") > -1) {
            return true;
        } else {
            return false;
        }
    }

    Example 5-4. Visual Basic

    Private Function processResultString(ByVal p_result As String) _
        As Boolean
        If p_result.IndexOf(">true</boolean>") > -1 Then
            Return True
        Else
            Return False
        End If
    End Function
  5. Scroll to the top of WebForm1 in code view and add the statements to import the namespaces of the System.Net.WebClient and System.Text.StringBuilder classes.

    Here’s how the import sections should appear:

    Example 5-5. C#

    // import the namespaces required for this example
    using System.Net;
    using System.Text;

    Example 5-6. Visual Basic .NET

    ‘ import the namespaces required for this example
    Imports System.Net
    Imports System.Text
  6. Finally, press Ctrl+Shift+B or select Build Solution from the Build menu to build the solution.

Procedure 5-4. Test the WebFormsClient application

  1. Press F5. Visual Studio .NET launches Internet Explorer and loads the WebFormsClient page.

  2. Type a credit card number into the Card Number text field, and then click the Validate button.

    If the number is valid, you will see the message "Number Valid." If the number is invalid or incorrectly formatted, you will see the message "Number Invalid."

Chapter 5 Quick Reference

To

Do This

Inspect the HTTP-GET and HTTP-POST protocol message formats used by an XML Web ­service

Open the service help page for the XML Web service you want to use. Click the link corresponding to the operation you want to invoke. The resulting Web page will contain the request and response formats for the HTTP protocols.

Invoke an XML Web service method using HTTP-GET or HTTP-POST

Construct an HTTP message containing any required data using the necessary message structure. Send the HTTP message to the URL for the XML Web service and process the response that is returned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.228.180