server HTTP header extractor(very simple)

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
poda19
Earned a small fee
Earned a small fee
Posts: 12
Joined: Wed Aug 10, 2011 7:27 pm

server HTTP header extractor(very simple)

Post by poda19 » Tue Aug 23, 2011 11:01 pm

This is for those (like me) who are using older versions, in wich wxHTTP doesn't support GetCookie and anyone who wants to extract HTTP server response headers.
it works fine for me but it may have bugs(specially in buffer sizings).

Code: Select all

#ifndef HDRXTRC_H
#define HDRXTRC_H

#include <wx/socket.h>
#include <wx/ffile.h>


    wxSocketClient mySock;
    mySock.SetFlags(wxSOCKET_WAITALL);
    wxIPV4address addr;
    addr.Hostname(server); //use a wxString name for server, example: wxT("google.com")
    addr.Service(80);      //web server port to connect to.

    //connect to the specified adress and port
    mySock.Connect(addr,1);

    //HTTP method and data to send to server:
    //GET example:
    mySock.Write("GET / HTTP/1.1\n\n",16);
    
    //POST example: (write any data you want to be sent to the server)
    //char* postdata="POST /xyz.php HTTP/1.1\r\nHost: xx.yy.zz\r\nConnection: keep-alive\r\n\r\nuser=blabla&password=pass";
    //send the information to server:
    //mySock.Write(postdata,Strlen(postdata)); //a char is 1byte in size, so we used Strlen to define buffer size.

    char buf[8000]; //buffer to save header data in. 8000 is enough in most cases. but you can change it to wathever you want.
    mySock.Read(buf,8000); //read server response to buf
    int i;
    wxFile headers;

    //create a text file to save headers in:
    headers.Open(_T("headers.txt"),headers.write);
    headers.Close();

    //append header data to headers.txt:
    wxString TempStr;
    for(i=0;buf[i];i++)
    {
        TempStr.Append(buf[i]);
        if(buf[i]=='\n')
            {
                if(TempStr.IsSameAs(wxT("\r\n"))) //headers are sepereated from HTML codes with an empty line.
                                                  //if we reach it, we exit the loop.
                    break;
                //you can also get only your desired headers using the following line:
                //if(tempStr.Contains(headerFilter))
                //the following, for example, filters headers so only the cookies are written to the file:
                //if(TempStr.Contains(_T("Set-Cookie"))){
                    headers.Open(_T("headers.txt"),headers.write_append);
                    headers.Write(TempStr) ;
                    headers.Close();
                //}
                TempStr.Clear();
            }
    }

#endif
enjoy!

Post Reply