Click here to Skip to main content
11,481,850 members (63,429 online)
Click here to Skip to main content

Making HTTP Communication from MFC/Windows Application

, 16 Apr 2001 198.1K 5.8K 110
Rate this:
Please Sign up or sign in to vote.
This articles shows one way for a MFC/Windows application to talk to a webserver using HTTP protocol.

 [Sample Image - 5K]

Introduction

Did you ever think of writing a Windows based application that talks to a web server and displays the results from a web server? If you didn't, well this is the right time to. "Why now?" you may ask. Because, a new interface, IXMLHttpRequest, is provided as part of Microsoft XML parser, which makes making HTTP requests effortless.

IXMLHttpRequest supports HTTP communication from a client to a server. The following is a snapshot of some of the important methods and properties:

IXMLHttpRequest Methods

  • open - Opens a HTTP connection.
  • send - Sends a HTTP request.
  • abort - Cancels HTTP request.

IXMLHttpRequest Properties

  • responseText - HTTP response text
  • status - HTTP status
  • statusText - HTTP status text

As you see, IXMLHttpRequest is an easy to use interface. To make a HTTP request, you just open a HTTP connection using the open() method, send the HTTP request using the send() method, and read the response message from the responseText property.

Enough of the theory. Let's get practical. Let's take a simple example to demonstrate how IXMLHttpRequest can be used.

Example

The sample MFC application displays stock price for a stock symbol from the web server. The MFC application will make a HTTP request to get the stock price from the web server. It will also display the HTTP status code and status message, just in case if anything goes wrong.

Architecture

Here is the architecture diagram of the sample application. It doesn't need much explanation. However, I wanted to draw your attention to the fact that this tiny application is a perfect 3 tier application. We have a UI tier, a business logic tier (ASP files), and a database tier.

 [Architecture Diagram - 3K]

User Interface

When you enter a stock symbol and hit the GetPrice button, that's when a synchronous HTTP request is sent to the server. The following self-explanatory code sends a HTTP request:

    // Open a HTTP connection
    HttpRequest->open("POST", 
                         "http://localhost/GetStockPrice.asp", 
                         vAsync, vUser, vPassword);

    // Form a HTTP request string
    CString szRequest;
    szRequest = "<RequestStockPrice Symbol='";
    szRequest += m_szSymbol;
    szRequest += "'/>";

    VARIANT vRequest;
    vRequest.vt = VT_BSTR;
    vRequest.bstrVal = szRequest.AllocSysString();

    // Send Http Request
    HttpRequest->send(vRequest);

The web server sends the response back in an XML string. Once the client gets the response text, it has to process the XML to fetch the stock price. Here is the code below which processes the response:

Note: The code section below does not list the complete code. Look in the source files for complete code.

    // Read response and status
    _bstr_t bsResponse = HttpRequest->responseText;

    // other code

    // Load response in to XML DOM Tree
    XMLDom->loadXML(bsResponse);

    // Process the response
    // Look for ResponseStockPrice node
    MSXML::IXMLDOMNodePtr XMLRootResponseNode = 
        XMLDom->selectSingleNode("ResponseStockPrice");

    if ( XMLRootResponseNode != NULL )
    {
        // Look for LastTradePrice node within ResponseStockPrice node
        MSXML::IXMLDOMNodePtr XMLLastTradeNode = 
          XMLRootResponseNode->selectSingleNode("LastTradePrice");

        if ( XMLLastTradeNode != NULL )
        {
            // Yep, we did get the stock price back
            CString szStockPrice((char*)XMLRootResponseNode->text);

            m_dblPrice = atof(szStockPrice);
            m_szErrorText = "OK";
            bRetVal = TRUE;
        }
    }

ASP file

The ASP file GetStockPrice.asp will receive the HTTP request in a XML form. Suppose you entered CSCO in the stock symbol edit box, this is how the request string will look like:

<RequestStockPrice Symbol='CSCO'/>

The ASP file reads the stock symbol from the above XML request string and makes a database query to fetch the stock price for this specific symbol. Here is how the database query will look like:

SELECT LastTradePrice FROM RealTimeStock where Symbol ='CSCO'

The final step is to form the XML response string, which is done by the code below:

Response.Write("<ResponseStockPrice>")

if ( rs.EOF = false ) then
    For each field in rs.Fields
        Response.Write("<")
        Response.Write field.Name
        Response.Write(">")

        Response.Write field.Value

        Response.Write("</")
        Response.Write field.Name
        Response.Write(">")
    Next
else
        'No record found
        Response.Write("<ErrorMesg>")
        Response.Write stockSymbol & " : Stock symbol not found in database"
        Response.Write("</ErrorMesg>")
end if

Response.Write("</ResponseStockPrice>")

The response string will look like this:

<ResponseStockPrice><LastTradePrice>20</LastTradePrice></ResponseStockPrice>

Database

I used a simple Access database which has two fields, Symbol and LastTradePrice, as shown in the figure below. Note that the field Symbol is the primary key.

 [Access Database - 10K]

XML Over HTTP

XML string is send over HTTP to accomplish our goal here. You may wonder whether this is a SOAP request. Though this application uses the same underlying principle of SOAP (i.e. XML Over HTTP), this is not a SOAP request since it doesn't adhere to the SOAP request protocols. Instead, it uses its own protocol for request and response strings.

Installation Notes

Download the client source files to your local computer. Download the server sources (ASP files and Access database file) to the root directory of your web server. Note that the sample application assumes that your web server runs on the same machine as the client. If your web server runs on a different machine, you have to change the URL name in IXMLHTTPRequest's open() method appropriately. This sample application will not work if the URL specified is wrong.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Dhandapani Ammasai(Dan in short) is a software delivery manager at a top tier IT company in India.

Comments and Discussions

 
Questiondownload files failure Pin
bestpeter311-Nov-13 20:51
memberbestpeter311-Nov-13 20:51 
GeneralMy vote of 4 Pin
Cees Meijer30-Jan-12 21:47
memberCees Meijer30-Jan-12 21:47 
GeneralMy vote of 5 Pin
haiiongshn3-Dec-10 2:13
memberhaiiongshn3-Dec-10 2:13 
QuestionWithout soap Pin
ERLN9-Apr-09 2:06
memberERLN9-Apr-09 2:06 
GeneralIXMLHTTPRequest Problem Pin
alireza_shokoie18-Sep-08 0:18
memberalireza_shokoie18-Sep-08 0:18 
GeneralCoInitalize / CoUninitialize Pin
Dlt7524-Mar-06 4:48
memberDlt7524-Mar-06 4:48 
QuestionIf anyone had done it? Pin
sandykm21-Mar-06 20:20
membersandykm21-Mar-06 20:20 
Questionwhat about c# Pin
raminshahriari21-Mar-06 16:51
memberraminshahriari21-Mar-06 16:51 
AnswerRe: what about c# Pin
gygabyte9-Apr-08 2:54
membergygabyte9-Apr-08 2:54 
Questionhow pass multi parameter Pin
wujun8-Aug-04 20:42
memberwujun8-Aug-04 20:42 
AnswerRe: how pass multi parameter [modified] Pin
Colerles20-Jul-06 22:25
memberColerles20-Jul-06 22:25 
GeneralHi Pin
IDispatch_200415-Jun-04 19:58
memberIDispatch_200415-Jun-04 19:58 
GeneralRe: Hi Pin
ronyy79-Sep-04 12:24
memberronyy79-Sep-04 12:24 
GeneralHi Pin
ptelang15-Jun-04 19:38
memberptelang15-Jun-04 19:38 
GeneralChaging Charset Pin
nitesh gaba24-Apr-04 0:52
membernitesh gaba24-Apr-04 0:52 
GeneralRe: Chaging Charset Pin
Vladimir Georgiev22-Aug-04 3:25
memberVladimir Georgiev22-Aug-04 3:25 
QuestionHow to send another data from vc to Web Server? Pin
angeltag23-Nov-03 21:35
memberangeltag23-Nov-03 21:35 
Questionhow to set proxy Pin
namnam15-Oct-03 18:27
membernamnam15-Oct-03 18:27 
Questionhow to get this working with php? Pin
irvine6-Oct-03 23:03
memberirvine6-Oct-03 23:03 
QuestionHow to Use UNICODE character? Pin
Yails3-Sep-03 19:48
memberYails3-Sep-03 19:48 
GeneralUsing Pin
Anonymous5-Jun-02 15:03
memberAnonymous5-Jun-02 15:03 
GeneralRe: Using Pin
M. Kale15-Oct-03 2:26
memberM. Kale15-Oct-03 2:26 
QuestionHow to maintain Same Session of ASP ? Pin
Unni12-Mar-02 23:33
memberUnni12-Mar-02 23:33 
AnswerRe: How to maintain Same Session of ASP ? Pin
Nathan Ridley15-Jun-03 21:32
memberNathan Ridley15-Jun-03 21:32 
GeneralError Pin
Björne24-Sep-01 6:07
memberBjörne24-Sep-01 6:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 17 Apr 2001
Article Copyright 2001 by Dhandapani Ammasai
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid