1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
void HttpPost()
{
//check if internet works
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
return;
}
//connect to website
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("www.cplusplus.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting...\n";
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0){
cout << "Could not connect";
return;
}
cout << "Connected.\n";
//this is the header, aka the data sent to the server. HERE is the problem!
const char* buf = "POST /login.do HTTP/1.1\n Content-Type: application/x-www-form-urlencoded\n Host: www.cplusplus.com "
" \n Content-Length: 120 \n w=login&y=1&to=www.cplusplus.com&l=myusername&p=mypassword \r\n\r\n";
//length of the sent header
cout << "Bytes sent: " << send(Socket, buf, strlen(buf), 0) << endl;
cout << "Printing outputs..." << endl;
// prints out HTML response
//counter, just for info, to check how many "streams" it takes to get the response
int count = 0;
//variable that holds the actual response
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0){
count++;
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
//finish things, else you have a process that never ended, probably a memory leak or something
closesocket(Socket);
WSACleanup();
cout << "done. Attempts: " << count << endl;
}
|