How to use OpenRequest() of CHttpConnection?

hshliang
hshliang used Ask the Experts™
on
I have trouble in understanding the use of OpenRequest of CHttpConnection and SendRequest or SendRequestEx of CHttpFile.
 
Let say I want to do something like:
https://website.ca/ABroker?ExternalAction=Asignon&username=Name&password=Password

How should I use the OpenRequest and SendRequest??

I have difficulty in finding examples.

Please help.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Author of the Year 2009

Commented:
The main parts are described here:

HOWTO: Simulate a Form POST Request Using WinInet (Q165298)
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q165298

The most common mistake is to forget to put:
   "Content-Type: application/x-www-form-urlencoded\r\n"
as a header string.

It just boils down to:

CHttpFile* pFile =pConnection->OpenRequest(...);

Then send the quest:

BOOL fRet= pFile->SendRequest( m_sHeaders, (LPVOID)(LPCTSTR)m_sFormData, nFormDataLen );

Then read the file:

CString sDest;
nActual= 1024;
char szBuf[ 1025 ];

while ( nActual > 0 ) {
     nActual= pFile->Read(szBuf, 1024);  
     szBuf[nActual] = '\0';

     sDest += szBuf;
     nSoFar += nActual;
     // SetDownloadProgress( nLen, nSoFar );
}
//SetDownloadProgress( nLen, nLen );

=-=--=-=-=
Note, the

   CInternetSession::OpenURL()

function is a little easier to use because you can skip a step or two (don't forget the Content-Type header! ).

-- Dan

Author

Commented:
Thank you so much Dan. My problem is to decipher what is header, what is parameters. Please use my example:
https://website.ca/ABroker?ExternalAction=Asignon&username=Name&password=Password
to write a OpenRequest() and SendRequest().

Like do I use "website.ca" as the ObjectName of "ABroker"?

OpenRequest(HTTP_VERB_POST, "website.ca"???? or "ABroker"? ....

How do I write the header?
Should I write:
CString StrHeader = "ExternalAction=Asignon&username=Name&password=Password";

Or Do I have to use AddHeader()

and
Do I write
SendRequest(StrHeader);??

Is the Optional the same as the DataBody (or Data to send) as I thought I have to a "BLANK" line between the header and the body.

As you can see I am a novice to the HTTP language and the names of various part of the statement can be confusing.

Please help!

Henry

Author

Commented:
Sorry I mean "AddRequestheader of CHttpFile in the comment.
Henrt
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Author of the Year 2009

Commented:
The URL is
   "https://website.ca/ABroker"
The FormData is:
CString sFormData=
   "ExternalAction=Asignon&username=Name&password=Password"

Try this for Headers:
CString sHeaders=
     "Accept: text/*\r\n"
     "User-Agent: Hack-o-Matic ver 0.01\r\n"
     "Content-Type: application/x-www-form-urlencoded\r\n"
;

>> SendRequest(StrHeader);??
You need to look in the documentation and the example in the link that I gave so that you will know how things work.

    pFile->SendRequest(
        sHeaders,
        (LPVOID)(LPCSTR)sFormData,
        sFormData.GetLength()
    ;

-- Dan

Author

Commented:
Dear Dan, Thank you.
I have use "website.ca" as _T("ServerNameHere") for GetHttpConnection, it is OK

Then I have tried "ABroker" for _T("FormActionHere") in OpenRequest, it gives an error of "Server or Address Name not resolve" error when SendRequest is called.

Then I tried using as you said "https:\\website.ca/ABroker" as the "FormActionHere" in OpenRequest, still it said "Server or Address Name not resolved".

The interesting thing is the error is raised when SendRequest is called.

Can it be error in GetHttpConnection (like certificate authorization etc) or Which one of "FormActionHere" is correct for the OpenRequest()

I have put sHeader and FormData as you suggested.

I have attemp sending the sample statement of
https://website.ca/ABroker?ExternalAction=Asignon&username=Name&password=Password
via Internet Explorer. It works well (except it warns me of certificate autherization). I have attemp to just GET the form page, and know that it needs CA.

The problem for me is : I don't know it the error happens in GetHttpConnection, OpenRequest OR SendRequest. As The exception is always thrown when SendRequest is called.

It makes it hard to debug.

Please help.

Henry


Author of the Year 2009

Commented:
>>Then I tried using as you said "https:\\website.ca/ABroker" as...

That will always fail because you have used backslashes in the address.  All slashes in URLS are forward slashes.

  https://website.ca/ABroker

Furthermore, in checking out the problem, I find that there is no such URL as

   https://website.ca/ABroker
or
   http://website.ca/ABroker

So the error message
    "Server or Address Name not resolved"
is simply correct and provides valuable information.   You need to be certain that the URL exists.  Then you can make progress in completing your program.

Try experimenting with a different site... one that is certain to exist.  

-- Dan

Author

Commented:
Sorry Dan
I admit I have some typo error in the comment. Actually, the  site (website.ca) is a fake name.
The actual site is https://tlpd1.moh.hnet.bc.ca/TeleplanBroker

I want to use MFC instead of the perl to access the site.
The original version in Perl is:

#-------------------------------------------------------------------------
#Start of Teleplan API
#-------------------------------------------------------------------------
sub init
{  
#Procedure parameters: webbase, webtimeout, directory, debug
#WEBBASE is the URL of the TeleplanBroker
#WEBTIMEOUT is the number of seconds before a timeout error occurs
#directory is the location to store temporary and downloaded files (this must end with the directory seperator)
#debug if its 1 then the $RESPONSE file in the directory specified will not be removed
#Initialize the UserAgent, retrieve cookies (if present)
#
#$WEBBASE = "https://tlpd1.moh.hnet.bc.ca/TeleplanBroker";
    my ($timeout);
    ($WEBBASE, $timeout, $DIR, $DEBUG) = @_;
    my ($cookiefile) = "cookies.txt";
    if (-d $DIR)
    {
        $COOKIE_JAR = HTTP::Cookies->new(File => $DIR . $cookiefile,
                                         AutoSave => 1,
                                         ignore_discard => 1);
        $UA = new LWP::UserAgent;
        $UA->agent("TeleplanPerl 1.0");
        $UA->from("TeleplanAPI");
        $UA->timeout($timeout);
        $UA->cookie_jar($COOKIE_JAR);
        $COOKIE_JAR->save();
        return $SUCCESS;
    }
    else
    {
        $Messages = "$DIR is not a valid directory";
        return $ERROR;
    }
}
#-------------------------------------------------------------------------
sub changePassword
{
#Procedure parameters: userid, password, new password, new password
#Parameters to TeleplanBroker are
#ExternalAction = "AchangePW"
#username         = $uid
#password         = $pw
#new.password     = $chgpw1
#confirm.password = $chgpw2
#Results from TeleplanBroker are:
#                                "SUCCESS" Password was changed successfully
#                                "FAILURE" Password was not changed
    my ($uid, $pw, $chgpw1, $chgpw2) = @_;
    my $request = POST $WEBBASE, [ 'username'         => $uid,
                                   'password'         => $pw,
                                   'new.password'     => $chgpw1,
                                   'confirm.password' => $chgpw2,
                                   'ExternalAction'   => 'AchangePW'];
    my $retVal = processRequest($request);      
    if ($retVal == $SUCCESS)
    {#valid response
       if ($Result ne "SUCCESS")
       {
           $retVal = $VALID;
       }
    }
    else
    {
       $retVal = $ERROR;
    }
    return $retVal;
}
#-------------------------------------------------------------------------
sub login
{
#Procedure parameters: userid, password
#Parameters to TeleplanBroker are
#ExternalAction = "AsignOn"
#Username = $uid
#password = $pw
#Results from TeleplanBroker are:
#                                "SUCCESS" for valid logon
#                                "FAILURE" for invalid logon
#                                "EXPIRED.PASSWORD" for valid username/password, user must change PW
#                                                   before the application will return a SUCCESS
    my ($uid, $pw) = @_;
    my $request = POST $WEBBASE, [ 'username'       => $uid,
                                   'password'       => $pw,
                                   'ExternalAction' => 'AsignOn'];
    my $retVal = processRequest($request);      
    if ($retVal == $SUCCESS)
    {#valid response
       if ($Result ne "SUCCESS")
       {
           $retVal = $VALID;
       }
    }
    else
    {
       $retVal = $ERROR;
    }
    return $retVal;
}
#-------------------------------------------------------------------------
sub logoff
{
#Procedure parameters:none
#Parameters to TeleplanBroker are
#ExternalAction = "AsignOff"
#Results from TeleplanBroker are: "SUCCESS" for valid logoff
    my $request = POST $WEBBASE, [ExternalAction => 'AsignOff'];
    my $retVal = processRequest($request);      
    if ($retVal == $SUCCESS)
    {#valid response
       if ($Result ne "SUCCESS")
       {
           $retVal = $VALID;
       }
    }
    else
    {
       $retVal = $ERROR;
    }
    return $retVal;
}
#-------------------------------------------------------------------------
 
As I don't know anything about Perl. I try to use VC++ to replace the above codes. I keep getting "Server not resolve" error. Even for as simple as a "POST" of AsignOff!!

Can you tell me how to write a MFC to simulate the functions of the above Perl code?

Many thanks
Henry
Author of the Year 2009
Commented:
The URL is
  "https://tlpd1.moh.hnet.bc.ca/TeleplanBroker"

The FormData is:
CString sFormData=
  "username=username&password=password&ExternalAction=WsignOn&Login=Login";

Try this for Headers:
CString sHeaders=
    "Accept: text/*\r\n"
    "User-Agent: Hack-o-Matic ver 0.01\r\n"
    "Content-Type: application/x-www-form-urlencoded\r\n"
;

The request is ...

   pFile->SendRequest(
       sHeaders,
       (LPVOID)(LPCSTR)sFormData,
       sFormData.GetLength()
   ;

=-=-=-=-
There is something going on with a certificate.  I had a hard time getting past this in some code I worked on in an earlier project.  To get to first base, I think you can use the browser (manually) to tell it to accept the cert.  Then it won't bother you when you try it programmatically.

If you up the points, I can offer more complete help.

-- Dan

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial