Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi,

I had a c++ application and I wand to call some link as below

www.mysite.com/register.php?app=[APP_NAME]&app_ver=[VERSION]& name=[NAME]&surname=[SURNAME]&email=[EMAIL]&gender=[GENDER]&country=[COUNTRY]&language=[LANGUAGE]
[NAME] = First name
[SURNAME] = Last name
[EMAIL] = email@domain.com
[GENDER] = male / female

This link shows "OK" if success else shows some error message.

Please tell me how execute this from c++ and check the result. Thanks in advance.
Posted
Comments
Sergey Alexandrovich Kryukov 24-Jul-12 11:13am    
What do you mean by "calling a Web site"? "Hey, Web site!"? :-)

What exactly do you want to achieve (ultimate goal, please), why, and what's the problem?
--SA
pasztorpisti 24-Jul-12 11:22am    
LOL :D Maybe this guy isn't familiar with the http protocol. I remember it was a mistery for me too for some time. :D
Sergey Alexandrovich Kryukov 27-Jul-12 17:58pm    
It's not so much important to be familiar with the protocol itself; in most cases, it's enough just to know what is it for. :-)
--SA

Hi there.

In my understanding, you want a C++ program that will retrieve the data that a web-browser would if you went to the url of your page.

It's reasonably simple, but far from trivial. There's a whole bunch of code around that deals with downloading a file using c/c++ (that's what you're doing - downloading it.) on the web. It's just not a file that exists on disk - no different to pretty much any forum page you care to visit-they're all dynamically generated too.

Here's some code that will download this page into memory, save it to disk and print it to screen. Modify to suit your needs, link to ws2_32.lib


C++
#include <windows.h>
#include <string>
#include <stdio.h>

using std::string;

HINSTANCE hInst;
WSADATA wsaData;

void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename)
{
    string::size_type n;
    string url = mUrl;

    if (url.substr(0,7) == "http://")
        url.erase(0,7);

    if (url.substr(0,8) == "https://")
        url.erase(0,8);

    n = url.find('/');
    if (n != string::npos)
    {
        serverName = url.substr(0,n);
        filepath = url.substr(n);
        n = filepath.rfind('/');
        filename = filepath.substr(n+1);
    }

    else
    {
        serverName = url;
        filepath = "/";
        filename = "";
    }
}

SOCKET connectToServer(char *szServerName, WORD portNum)
{
    struct hostent *hp;
    unsigned int addr;
    struct sockaddr_in server;
    SOCKET conn;

    conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (conn == INVALID_SOCKET)
        return NULL;

    if(inet_addr(szServerName)==INADDR_NONE)
    {
        hp=gethostbyname(szServerName);
    }
    else
    {
        addr=inet_addr(szServerName);
        hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
    }

    if(hp==NULL)
    {
        closesocket(conn);
        return NULL;
    }

    server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
    server.sin_family=AF_INET;
    server.sin_port=htons(portNum);
    if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
    {
        closesocket(conn);
        return NULL;
    }
    return conn;
}

int getHeaderLength(char *content)
{
    const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r";
    char *findPos;
    int ofset = -1;

    findPos = strstr(content, srchStr1);
    if (findPos != NULL)
    {
        ofset = findPos - content;
        ofset += strlen(srchStr1);
    }

    else
    {
        findPos = strstr(content, srchStr2);
        if (findPos != NULL)
        {
            ofset = findPos - content;
            ofset += strlen(srchStr2);
        }
    }
    return ofset;
}

char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut)
{
    const int bufSize = 512;
    char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize];
    char *tmpResult=NULL, *result;
    SOCKET conn;
    string server, filepath, filename;
    long totalBytesRead, thisReadSize, headerLen;

    mParseUrl(szUrl, server, filepath, filename);

    ///////////// step 1, connect //////////////////////
    conn = connectToServer((char*)server.c_str(), 80);

    ///////////// step 2, send GET request /////////////
    sprintf(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str());
    strcpy(sendBuffer, tmpBuffer);
    strcat(sendBuffer, "\r\n");
    sprintf(tmpBuffer, "Host: %s", server.c_str());
    strcat(sendBuffer, tmpBuffer);
    strcat(sendBuffer, "\r\n");
    strcat(sendBuffer, "\r\n");
    send(conn, sendBuffer, strlen(sendBuffer), 0);

//    SetWindowText(edit3Hwnd, sendBuffer);
    printf("Buffer being sent:\n%s", sendBuffer);

    ///////////// step 3 - get received bytes ////////////////
    // Receive until the peer closes the connection
    totalBytesRead = 0;
    while(1)
    {
        memset(readBuffer, 0, bufSize);
        thisReadSize = recv (conn, readBuffer, bufSize, 0);

        if ( thisReadSize <= 0 )
            break;

        tmpResult = (char*)realloc(tmpResult, thisReadSize+totalBytesRead);

        memcpy(tmpResult+totalBytesRead, readBuffer, thisReadSize);
        totalBytesRead += thisReadSize;
    }

    headerLen = getHeaderLength(tmpResult);
    long contenLen = totalBytesRead-headerLen;
    result = new char[contenLen+1];
    memcpy(result, tmpResult+headerLen, contenLen);
    result[contenLen] = 0x0;
    char *myTmp;

    myTmp = new char[headerLen+1];
    strncpy(myTmp, tmpResult, headerLen);
    myTmp[headerLen] = NULL;
    delete(tmpResult);
    *headerOut = myTmp;

    bytesReturnedOut = contenLen;
    closesocket(conn);
    return(result);
}


int main()
{
    const int bufLen = 1024;
    char *szUrl = "http://www.codeproject.com/Questions/427350/calling-a-website-from-cplusplus";
    long fileSize;
    char *memBuffer, *headerBuffer;
    FILE *fp;

    memBuffer = headerBuffer = NULL;

    if ( WSAStartup(0x101, &wsaData) != 0)
        return -1;


    memBuffer = readUrl2(szUrl, fileSize, &headerBuffer);
    printf("returned from readUrl\n");
    printf("data returned:\n%s", memBuffer);
    if (fileSize != 0)
    {
        printf("Got some data\n");
        fp = fopen("downloaded.file", "wb");
        fwrite(memBuffer, 1, fileSize, fp);
        fclose(fp);
//        SetDlgItemText(hwndDlg, IDC_EDIT4, headerBuffer);
//        SetDlgItemText(hwndDlg, IDC_EDIT5, memBuffer);
        delete(memBuffer);
        delete(headerBuffer);
    }

    WSACleanup();
    return 0;
}
 
Share this answer
 
Comments
Richard MacCutchan 24-Jul-12 15:37pm    
I wonder why this didn't get accepted as the solution, when it fully answers the question?
enhzflep 24-Jul-12 15:46pm    
You and I both. I thought the OP must be offline when I saw your comment roll-in. Now I see that (like I suspect you have been) I was fooled by the green header on solution 1. A quick check of the QA list indicates the Q is yet to have a solution accepted.
I guess the OP is still offline. (?)
Richard MacCutchan 24-Jul-12 15:57pm    
So where did the green header come from, I think we should be told? Maybe it's on votes.
enhzflep 24-Jul-12 16:03pm    
Yeah, that was the tentative conclusion I'd come to.
Not quite sure what the threshold/trigger is. I guess all of the following are possible.
Total # of 5 votes
Total of raw votes
Total of weighted votes

Dunno, must be about tea'o'clock though. :)
There's an useful article in CodeProject about that:

CHttpClient - A Helper Class Using WinInet[^]

It includes responses and file management.
 
Share this answer
 
Comments
Binu MD 25-Jul-12 2:07am    
Thank you all for your support its worked :)
Sergey Alexandrovich Kryukov 27-Jul-12 18:00pm    
5ed, one of the possible solutions.
--SA
ShellExecute(NULL, "open", "http://www.mysite.com", NULL, NULL, SW_SHOWNORMAL);

This brings up a browser. If you want to parse the output then you have to use a http client library like cURL[^] to download a response to your post or get request and then you have to parse that output.

Note: If you want to communicate with a webserver via http and you can program the server as well (cgi or servlet) then you can create some "gates" inside your webserver, some urls that give a response other then a html page (like webservices), for example your url could respond with xml or json or custom text that is easy to parse by your c++ program. If you are new to http: "Calling your webserver" means creating a tcp connection with the server, sending a HTTP request (HTTP protocol[^]), and then reading out the response on the same socket. The response can be anything, even binary data, it can be sent by your servlet or cgi program from inside the server.
There are libraries that do the job for you on the client side in your c++ program (http client libraries like libcURL). If you don't need a response, then just start a browser for the user with the link using ShellExecute().
 
Share this answer
 
v4
Comments
Binu MD 25-Jul-12 2:07am    
Thank you all for your support its worked :)
Sergey Alexandrovich Kryukov 27-Jul-12 18:03pm    
This time, I up-voted it with 4. This should be more fair to enhzflep... (as I saw, you also up-voted his answer) :-) Running an external process may not be good for many purposes as processes are isolated. I understand the question itself is not very good... :-)
--SA
pasztorpisti 27-Jul-12 18:12pm    
Fair enough, I also don't feel 100% good about my answer because I don't really like the bloat code of cURL but I don't know a really simple and good HTTP client library as a replacement. 2 years ago implemented a simple drop in HTTP client library that took the tests on many platforms but unfortunately that code isnt my property to publish. enhzflep's code is short and perfect as an answer and tutorial (5), it just doesn't handle some cases of HTTP.
Sergey Alexandrovich Kryukov 27-Jul-12 18:18pm    
Agree.
Cheers,
--SA
ranjithkumar81 12-Jun-14 6:16am    
Thanks for your source code to get data from website and its worked.

But some times exe hangs or crashing , in place of memory release membuffer.

Could you provide some solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900