gpt4 book ai didi

c++ - 如何在 C++ 和 Wininet 中使用 HTTP POST

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:50:49 25 4
gpt4 key购买 nike

我正在使用 POST 将两个变量的值发送到 PHP 服务器。使用 Wininet 的 C++ 应用程序连接到服务器端脚本,但它没有正确发送数据,而是在使用 POST 发送的参数中显示空字段。

 #include <windows.h> #include <wininet.h> #include <stdio.h> #include <fstream> #include <cstring> 
#pragma comment (lib, "Wininet.lib")
#define SIZE 128

int main() {

HINTERNET Initialize, Connection, File;
DWORD dwBytes;
static const char *postData = "name=Jack+Din&age=38";

LPSTR accept1[2] = { "Accept: */*", NULL };

const char * const frmdata = "name=Arun+Pushkar&age=38";

static const char *hdrs[] = { "Content-Type: application/x-www-form-urlencoded" };

static const char *accept[] = { "*/*", NULL };

char ch;

Initialize = InternetOpen(L"HTTPGET", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

if (!Initialize)
{
printf("Failed to open session\n");
exit(0);
}

Connection = InternetConnect(Initialize, L"192.168.1.10", INTERNET_DEFAULT_HTTP_PORT,
NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);

File = HttpOpenRequest(
Connection,
L"POST",
L"/trydata.php",
L"HTTP/1.0",
NULL,
NULL,
INTERNET_FLAG_NO_CACHE_WRITE,
0);

unsigned long dataLen = strlen((char*)frmdata)+1;

bool res = HttpSendRequest(
File, // file to which reply will come
(LPCWSTR)hdrs,
0,
(char*)frmdata, // post variables to be send
dataLen); // length of data send

if (res)
{
std::ofstream webSource;

webSource.open("a.html");

while (InternetReadFile(File, &ch, 1, &dwBytes))
{
if (dwBytes != 1)break;
webSource << ch;
}
webSource.close();
}

InternetCloseHandle(File);
InternetCloseHandle(Connection);
InternetCloseHandle(Initialize);

return 0;

}

服务器端脚本是

<?php
$yourname = isset($_POST['name']) ? $_POST['name'] : 'no name';
$yourage = isset($_POST['age']) ? $_POST['age'] : 'no age';
echo "Hello".htmlspecialchars($yourname). "!";
echo "Your Age".htmlspecialchars($yourage). "!";
?>

当我运行此 C++ 代码时,我在 a.html 中得到以下内容:

Hello no Name!Your Age no Age!

最佳答案

我会使用 ATL Server 类来做同样的事情。这是示例:

CAtlHttpClient client; 
AtlNavigateData navData;
LPCSTR lpData = "data=toto";
navData.SetMethod(ATL_HTTP_METHOD_POST);
navData.SetPostData((BYTE*)lpData, lstrlenA(lpData), _T("application/x-www-form-urlencoded"));
client.Navigate(_T("mysite.net"), _T("myscript.php"), &navData);
const char* pszBody = (const char*)client.GetBody();

关于c++ - 如何在 C++ 和 Wininet 中使用 HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29249344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com