Hi
How to post data to http server using vc++?
I can manage to post in vb.net.
Thanks
// SendHTTP: Main entry point for this code. // url - The URL to GET/POST to/from. // headers - Headers to be sent to the server. // post - Data to be posted to the server, NULL if GET. // postLength - Length of data to post. // req - Contains the message and headers sent by the server. // returns 1 on failure, 0 on success. int SendHTTP(LPCSTR url,LPCSTR headers,BYTE *post,DWORD postLength,HTTPRequest *req) { WSADATA WsaData; SOCKADDR_IN sin; SOCKET sock; char buffer[1024]; char protocol[20],host[128],request[2048]; int l,port,chars,err; MemBuffer headersBuffer,messageBuffer; BOOL done;
// Parse the URL ParseURL(url,protocol,sizeof(protocol)-1,host,sizeof(host)-1,request,sizeof(request)-1,&port); if(strcmp(protocol,"HTTP")) return 1;
// Init Winsock err = WSAStartup (0x0101, &WsaData); if(err!=0) return 1; sock = socket (AF_INET, SOCK_STREAM, 0); if ( (unsigned int)socket == INVALID_SOCKET) return 1; // Connect to web sever sin.sin_family = AF_INET; sin.sin_port = htons( (unsigned short)port ); sin.sin_addr.s_addr = GetHostAddress(host); if( connect (sock,(LPSOCKADDR)&sin, sizeof(SOCKADDR_IN) ) ) return 1; // Send request if( !*request ) lstrcpyn(request,"/",sizeof(request)-1); if( post == NULL ) SendString(sock,"GET "); else SendString(sock,"POST "); SendString(sock,request); SendString(sock," HTTP/1.0\r\n"); SendString(sock,"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, */*\r\n"); SendString(sock,"Accept-Language: en-us\r\n"); SendString(sock,"Accept-Encoding: gzip, deflate\r\n"); SendString(sock,"User-Agent: Mozilla/4.0\r\n"); if(postLength) { wsprintf(buffer,"Content-Length: %ld\r\n",postLength); SendString(sock,buffer); } SendString(sock,"Host: "); SendString(sock,host); SendString(sock,"\r\n"); if( (headers!=NULL) && *headers ) SendString(sock,headers);
// Send a blank line to signal end of HTTP headers SendString(sock,"\r\n"); if( (post!=NULL) && postLength ) send(sock,(char*)post,postLength,0);
// Read the result // First read HTTP headers MemBufferCreate(&headersBuffer ); chars = 0; done = FALSE; while(!done) { l = recv(sock,buffer,1,0); if(l<0) done=TRUE; switch(*buffer) { case '\r': break; case '\n': if(chars==0) done = TRUE; chars=0; break; default: chars++; break; } MemBufferAddByte(&headersBuffer,*buffer); } req->headers=(char*)headersBuffer.buffer; *(headersBuffer.position) = 0; // Now read the HTTP body MemBufferCreate(&messageBuffer); do { l = recv(sock,buffer,sizeof(buffer)-1,0); if(l<0) break; *(buffer+l)=0; MemBufferAddBuffer(&messageBuffer,(BYTE*)buffer,l); } while(l>0); *messageBuffer.position = 0; req->message = (char*)messageBuffer.buffer; req->messageLength = (messageBuffer.position-messageBuffer.buffer); // Cleanup closesocket(sock); return 0; }