我不是用C ++编程,但是我要求有人这样做,所以如果我的问题很简单或愚蠢,我很抱歉。
我需要一个使用HttpOpenRequest/HttpSendRequest
对象的简单示例,以便将JSON
数据发送到某个Web服务/网站。
谢谢
答案 0 :(得分:2)
这是一个将JSON字符串发送到http://hostname/path/scriptname
的非常简单的示例。您将需要根据需要添加正确的错误检查,状态代码检查等:
HINTERNET hInternet = InternetOpen(_T("MyApp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect(hInternet, _T("hostname"), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
LPTSTR rgpszAcceptTypes[] = {_T("application/json"), NULL};
HINTERNET hRequest = HttpOpenRequest(hConnect, _T("POST"), _T("/path/scriptname"), NULL, NULL, rgpszAcceptTypes, 0, 0);
HttpAddRequestHeaders(hRequest, _T("Content-Type: application/json\r\n"), -1, HTTP_ADDREQ_FLAG_ADD);
char *JsonData = "..."; // your actual JSON data here
HttpSendRequest(hRequest, NULL, 0, JsonData, strlen(JsonData))
DWORD StatusCode = 0;
DWORD StatusCodeLen = sizeof(StatusCode);
HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &StatusCode, &StatusCodeLen, NULL);
if (StatusCode == 200)
{
// use InternetQueryDataAvailable() and InternetReadFile()
// to read any response data as needed...
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);