CHTTPSocket - Class to Explore Web

Hmm, now show time! Here is CHTTPSocket class with full source code, full qualified, one step, HTTP client. Can fetch pages from web, no problems if You try virtual host. If You use proxy server, only set some variables and get it worked also. I also compile sample application which You can download and test. Ok, leme start with exe sample. Download dtsexe.zip, rename to dtsexe.zip, and uzip it, 37K in length and usage very simple:

//---------------------------------------------------------
//call style:
//---------------------------------------------------------
// dts.exe /URL <url> [/PRX <phost>] [/PRT <pport>]
//---------------------------------------------------------
// where /URL - U see
//       /PRX - proxy's internet address
//       /PRT - proxy's port
//---------------------------------------------------------
// You must have KERNEL32.DLL, USER32.DLL and WS2_32.DLL 
// installed.
//---------------------------------------------------------
For example:
dts.exe /URL http://www.tair.freeservers.com for direct access
or: (the following should all go on one line)
dts.exe /URL http://www.yahoo.com /PRX 127.0.0.1 
        /PRT 8080 access via proxy
If this isn't clear, the attached demo should help.
/**********************************************************
HTTP socket - DTS Project
Copyright (C) 2000 by Tair Abdurman, All Rights Reserved
http://www.tair.freeservers.com, dts@tair.freeservers.com
No any part of this code can be used in comercial purposes.
***********************************************************

#include <stdio.h>
#include "httpsocket.h"

/**********************************************************
Sample derived class
***********************************************************

class CMySock : public CHTTPSocket
{
char szErrMessage[255];
public:
 void OnError();
 void OnResponse(); 
};

//error trigger
void CMySock::OnError()
{
 wsprintf(szErrMessage,"Error: %d, %d, %s",
  m_nErrCode, m_nExtErrCode, m_nErrInfo);

 MessageBox(NULL,szErrMessage,"Error",MB_OK);
 CHTTPSocket::OnError();
};


//response trigger
void CMySock::OnResponse()
{
 printf("----m_ulResponseSize=%d\r\n",m_ulResponseSize);
 printf("%s\r\n",(char *)m_szResponse);

 CHTTPSocket::OnResponse();
};

//---------------------------------------------------------
//call style:
//---------------------------------------------------------
// dts.exe /URL http://www.yahoo.com [/PRX 127.0.0.1] [/PRT 8080]
//---------------------------------------------------------
// where /URL - U see
//       /PRX - proxy's internet address
//       /PRT - proxy's port
//---------------------------------------------------------
// You must have KERNEL32.DLL, USER32.DLL and 
// WS2_32.DLL installed.
//---------------------------------------------------------
/**********************************************************
main. entry point for service
***********************************************************
void main(int argc,char* argv[])
{
 CMySock cs;
 cs.m_bUseProxy=FALSE;
 int i=0;
 char* page=NULL;
 char* serverHost=NULL;
 char* serverPort=NULL;

 while(i<argc)
 {
  if (strcmp(argv[i],"/URL")==0)
  {
   if (argv[++i]!=NULL)
   page=argv[i];
   else
   page=NULL;
  } 

  if (strcmp(argv[i],"/PRX")==0)
  {
   if (argv[++i]!=NULL)
    serverHost=argv[i];
   else
    serverHost=NULL;
  }

  if (strcmp(argv[i],"/PRT")==0)
  {
   if (argv[++i]!=NULL)
    serverPort=argv[i];
   else
    serverPort=NULL;
  }
  i++;
 }

 if (page==NULL)
 {
  cs.ThrowError(0,0,"Please specify URL to fetch!");
  return;
 }

 if (serverHost!=NULL)
 {
  //sets proxy server's internet address
  cs.SetServerHost((const char*)serverHost);

  i=0;
  if(serverPort!=NULL)
  i=atoi(serverPort);
  if (i==0)
  i=8080;
  
  //sets proxy server's port number (8080 by default)
  cs.m_nServerPort=i;
  
  //says use proxy to CHTTPSocket derived class
  cs.m_bUseProxy=TRUE;
 }


 printf("URL to fetch: %s\r\n",page);
 printf("Use proxy %s\r\n",serverHost);
 printf("Port for proxy %d\r\n",i);

 //page request here
 cs.Request(page);
}
and CHTTPSocket interface:
/********************************************************
clicksocket.h
*********************************************************

#ifndef __HTTPSOCKET__H__
#define __HTTPSOCKET__H__


#include <windows.h>
//rem next  line if no debug dump wanted 
#define DEBON
#include <stdio.h>

//default send and recieve timeouts in sec
#define HTTPRTIMEOUTDEF 90000
#define HTTPSTIMEOUTDEF 90000

#define MAXHOSTLENGTH   65
#define MAXIPLENGTH     16
#define MAXBLOCKSIZE    1024
#define MAXURLLENGTH    255
#define MAXHEADERLENGTH 269

//primary error codes
#define ERR_OK           0
//if this error occurs, extended code is WSA's error code
#define ERR_WSAINTERNAL  1
#define ERR_URLNOTHING   2
#define ERR_URLTOOLONG   3
#define ERR_HOSTUNKNOWN  4
#define ERR_PROXYUNKNOWN 5
#define ERR_PROTOPARSE   6
#define ERR_BADHOST      7
#define ERR_BADPORT      8


class CHTTPSocket
{
 static int nInstanceCount;

SOCKET              sckHTTPSocket;
struct sockaddr_in  sinHTTPSocket;
struct sockaddr_in  sinHTTPServer;
// remote server host address,
// size 64 bytes,65th set to \0
	   char         m_szServerHost[MAXHOSTLENGTH];
// host
	   char         m_szHost[MAXHOSTLENGTH];
// requested URI/URL
	   char         m_szURL[MAXURLLENGTH];
// remote server IP address, size 15 bytes, 16th set to \0
	   char         m_szServerHostIP[MAXIPLENGTH];
//-- Win32 specific
WSADATA           wsaData;

void szcopy(char* dest,const char* src,int nMaxBytes);
void szsent(SOCKET sckDest,const char* szHttp);

public:
 // set to TRUE in InitInstance if TIME_WAIT not need ()
 BOOL  m_bNoTimeWait;

 // recieve timeout change in InitInstance
 int   m_nRecvTimeout;

 // send timeout change in InitInstance
 int   m_nSendTimeout;

 // remote server port
 int m_nServerPort;

 // use proxy flag
 BOOL  m_bUseProxy;

 // error code
 int m_nErrCode;

 // extended error code;
 int m_nExtErrCode;

 // error info
 char m_nErrInfo[255];

 // response content
 LPVOID m_szResponse;

 // response size
 ULONG m_ulResponseSize;

public:

 //const/destr
 CHTTPSocket();
 virtual ~CHTTPSocket();
   
 //utils
 // sets proxy or http server's host
 void SetServerHost(const char* src);

 // sets proxy or http server's ip 
 //(should be skipped if SetServerHost used)
 void SetServerHostIP(const char* src);

 //starts request transaction
 void Request(const char* url="http://www.tair.freeservers.com");

 //used for free memory allocated for page
 //(should be skipped if You use CHTTPSocket::OnResponse 
 //call in OnResponse)
 void memPostup();

 //fire your OnError with specific error cdes and message
 void ThrowError(int err, int xerr, const char* errdesc);
   
 //overridable

 //shoul be used for additional inits
 virtual BOOL InitInstance();

 //trigger on any transaction error 
 //(its great if U will call CHTTPSocket::OnError inside,
 //to free allocated memory pages)
 virtual void OnError();

 //trigger on response recieved
 //(its great if U will call CHTTPSocket::OnResponse inside,
 //to free allocated memory pages)
 virtual void OnResponse();
};

#endif

Downloads

Download demo project - 15 Kb


Comments

  • De alta calidad 2012 GHD secador de pelo, comprar ghd Edición Limitada pueden obtener

    Posted by wanzilucky on 06/05/2013 06:25pm

    [url=http://comprar-ghd.manifo.com/]Comprar ghd[/url] Tanto 10€ de cada venta de la styler ghd PINK Cherry Blossom, como 6€ de la venta de ghd air PINK Cherry Blossom serán destinados a proyectos de investigación del Cáncer de mama a través de las Fundaciones FERO y Sandra Ibarra de Solidaridad Frente al Cáncer. [url=http://comprar-ghd.manifo.com/]planchas ghd[/url] Existe una selección de productos GHD cabello alisado para elegir. Sus alisadores de cerámica particular, sin duda son una sustancia del estado-de-arte que ofrece la temperatura ideal a través de la peluquería.Estos guardias específicas sabios atributos de su plancha de corriente a través de la destrucción gracias a la humedad normal del agua acumulación o condensación de la porcelana en la unidad. Como resultado de los avances presentados, simplemente GHD en sus soluciones de planos de hierro, la empresa revolucionó adecuadamente sus patrones, junto con funciones más populares de una simple salón de grado de plancha. [url=http://planchas-ghd.manifo.com/]planchas ghd[/url] Ellos alisar el cabello mucho más y en ningún momento. Mientras usted está usando algún tipo de protección del cabello, el cabello no recibe todo seco y muy rizado. Se trata de una compra excelente y buena inversión.La principal preocupación de pocos clientes es el calor algo incontrolable. Estos hierros no vienen con un termómetro la temperatura ajustable, de manera que se está fuera de su control. Estos hierros conseguir demasiado caliente. Al día siguiente, que le huele el pelo quemado.Son muy caliente cuando la luz roja parpadea y hay que tener cuidado al usar y definitivamente el uso de algún tipo de protección en la salud del cabello.

    Reply
  • Very very good.

    Posted by Legacy on 12/18/2003 12:00am

    Originally posted by: Steve Hu

    Very very good.

    Reply
  • Help!!!

    Posted by Legacy on 06/19/2003 12:00am

    Originally posted by: SANJAY SAMUEL

    hi Abdur,
    I was going through your code and I found it to be very good. Abdur I have an query. suppose I run your exe in some part of the world and want to connect to some machine present in some other part of the world present behind the proxy.(THE SERVER PULIC IP IS KNOWN TO ME). what i exactly want is to run an exe present in the proxy remotely using your exe. Is it possible . Please send me this query.If you can help me with the code I would be very very greatful to you.
    Thank You.

    .........For the nice code sent.........

    Yours

    Sanjay Samuel

    Reply
  • wonderful class

    Posted by Legacy on 02/17/2003 12:00am

    Originally posted by: venkatesh

    hi,
    this is really a wonderful class. I was searching for this type of class since a week ..

    thank you
    venki

    Reply
  • HTTP Request within one send

    Posted by Legacy on 11/06/2002 12:00am

    Originally posted by: Anderl

    I made the experience, that the class like it is does not work for all servers.
    Some server need to receive the HTTP Request within one send.

    So just do not send each line. Store the Request in a string variable and then send the command at once.
    This should work.

    Anderl

    Reply
  • methods implementing on http server

    Posted by Legacy on 05/08/2002 12:00am

    Originally posted by: tom skaria

    sir,
    i am studying for MCA and i am doing a http server project as
    part of partial fulfillment of my carriculam.

    i have implemented the GET and POST methods.
    now i wanted to do HEAD,PUT and DELETE methods.


    the method which i completed(GET and POST)in very simple as u see.
    here i am describing my completed portion.
    1.i writtern a tcp socket program and the client is Lynx or Internet
    explorer.

    2.in that socket pgm i called a fuction to parse the name and
    passoword.but in my project the parsing is only possible for a
    name and a password which i given the name and password in the
    program itself.eg:strcmp(tname,"tom")==0 &&(tpassword,"tom1")....like that

    Here the problem is,it is not checking the name and password more
    than one person.so as to get more database,what i have to do for the
    creation of a database?
    so,how i can create a database in C ,is there any way to connect
    ODBC or ACCESS to this C program?

    3.my second doubt is how to implement the HEAD,PUT and DELETE methods.i have
    no idea of that.is it requre any HTML page that support these Methods?

    if u need further more about my programm .ask me.

    so sir please advice me for this problem.

    so u mail me to the id:tomskaria@rediffmail.com
    from
    tom

    Reply
  • methods implementing on http server

    Posted by Legacy on 05/08/2002 12:00am

    Originally posted by: tom skaria

    sir,
    i am studying for MCA and i am doing a http server project as
    part of partial fulfillment of my carriculam.

    i have implemented the GET and POST methods.
    now i wanted to do HEAD,PUT and DELETE methods.


    the method which i completed(GET and POST)in very simple as u see.
    here i am describing my completed portion.
    1.i writtern a tcp socket program and the client is Lynx or Internet
    explorer.

    2.in that socket pgm i called a fuction to parse the name and
    passoword.but in my project the parsing is only possible for a
    name and a password which i given the name and password in the
    program itself.eg:strcmp(tname,"tom")==0 &&(tpassword,"tom1")....like that

    Here the problem is,it is not checking the name and password more
    than one person.so as to get more database,what i have to do for the
    creation of a database?
    so,how i can create a database in C ,is there any way to connect
    ODBC or ACCESS to this C program?

    3.my second doubt is how to implement the HEAD,PUT and DELETE methods.i have
    no idea of that.is it requre any HTML page that support these Methods?

    if u need further more about my programm .ask me.

    so sir please advice me for this problem.

    so u mail me to the id:tomskaria@rediffmail.com
    from
    tom

    Reply
  • http

    Posted by Legacy on 05/08/2002 12:00am

    Originally posted by: tom skaria

    sir,
    i am studying for MCA and i am doing a http server project as
    part of partial fulfillment of my carriculam.

    i have implemented the GET and POST methods.
    now i wanted to do HEAD,PUT and DELETE methods.


    the method which i completed(GET and POST)in very simple as u see.
    here i am describing my completed portion.
    1.i writtern a tcp socket program and the client is Lynx or Internet
    explorer.

    2.in that socket pgm i called a fuction to parse the name and
    passoword.but in my project the parsing is only possible for a
    name and a password which i given the name and password in the
    program itself.eg:strcmp(tname,"tom")==0 &&(tpassword,"tom1")....like that

    Here the problem is,it is not checking the name and password more
    than one person.so as to get more database,what i have to do for the
    creation of a database?
    so,how i can create a database in C ,is there any way to connect
    ODBC or ACCESS to this C program?

    3.my second doubt is how to implement the HEAD,PUT and DELETE methods.i have
    no idea of that.is it requre any HTML page that support these Methods?

    if u need further more about my programm .ask me.

    so sir please advice me for this problem.

    so u mail me to the id:tomskaria@rediffmail.com
    from
    tom

    Reply
  • It doesn't work for pages that require CGI params?

    Posted by Legacy on 10/16/2001 12:00am

    Originally posted by: Grace

    my URL is something like:
    http://XYZ.com/cgi-bin/ho/hey/MyCGI.cgi?A=0&B=8&C=0&D=0

    Seems like A=0&B=8&C=0&D=0 are ignored


    If I typed the whole URL on the browser, it works!

    HELP~~~~~


    Reply
  • Server responds : "the param is incorrect"

    Posted by Legacy on 10/16/2001 12:00am

    Originally posted by: oliviersax

    I am trying this wonderfull program from behind my proxy server but it does not work :
    
    dts.exe /URL www.altavista.com /PRX proxy.cv.com /PRT 3128
    The server response is :
    <html>
    <head>
    <title>Error</title>
    </head>
    <body>
    The parameter is incorrect.
    </body>
    </html>

    When i test this program with an URL from my intranet (without the proxy), it works very well !!!

    What can be wrong ?

    Thanks !

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds