Wednesday, April 26, 2017

C++ Function For HTTP POST

This is a function I use often to create POST requests by passing in a string.


int httpSendPost(string post)
{
 char* buf = &post[0];
 GetLastError();
 HINTERNET hInternet, hConnect, hRequest;
 hInternet = InternetOpen(TEXT("My UserAgent"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL);
 hConnect = InternetConnect(hInternet, TEXT("www.site.com"), INTERNET_DEFAULT_HTTP_PORT, 0, 0, INTERNET_SERVICE_HTTP, 0, 0);
 hRequest = HttpOpenRequest(hConnect, TEXT("POST"), TEXT("/hi/there"), 0, 0, 0, INTERNET_FLAG_RELOAD, 0);
 if (hRequest == NULL)
  cout << "HttpOpenRequest error code: " << GetLastError() << endl;
 if (!HttpSendRequest(hRequest, 0, 0, buf, post.length()))
  cout << "HttpSendRequest error code: " << GetLastError() << endl;
 InternetCloseHandle(hInternet);
 InternetCloseHandle(hConnect);
 InternetCloseHandle(hRequest);
 return 0;
}

I should also probably have the "www.site.com" and "/hi/there" be passed in via parameters, but meh, it works.

No comments:

Post a Comment