使用 WinHttp 请求时,调用会成功进行,但是取决于调用是否需要时间才能在站点中填充,那么该值将不会返回任何内容并且不会报告任何错误。我们使用 cfc 文件作为 api 返回的响应。有些调用会起作用,而另一些则不会(通常需要 2 秒以上才能返回调用并填充数据)。
遗憾的是,API 是私有的,我无法提供调用(专有信息)。但我愿意接受所有建议,并将提供调用数据的代码(不包含任何专有数据)。
string response;
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen(L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
// Specify an HTTP server.
if (hSession) {
hConnect = WinHttpConnect(hSession, s2ws(host).c_str(),
INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!WinHttpSetTimeouts(hSession, 600000, 600000, 600000, 600000))
printf("Error %u in WinHttpSetTimeouts.\n", GetLastError());
}
// Create an HTTP request handle.
if (hConnect)
hRequest = WinHttpOpenRequest(hConnect, L"GET", s2ws(call).c_str(),
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH | WINHTTP_FLAG_SECURE);
// Send a request.
if (hRequest) {
bResults = WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
0, 0);
}
// End the request.
if (bResults) {
bResults = WinHttpReceiveResponse(hRequest, 0);
}
// Keep checking for data until there is nothing left.
if (bResults) {
do {
// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {
printf("Error %u in WinHttpQueryDataAvailable.\n",
GetLastError());
break;
}
if (!dwSize)
break;
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize + 1];
if (!pszOutBuffer) {
printf("Out of memory\n");
break;
}
// Read the data.
ZeroMemory(pszOutBuffer, dwSize + 1);
if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded))
printf("Error %u in WinHttpReadData.\n", GetLastError());
else {
response = response + string(pszOutBuffer);
}
// Free the memory allocated to the buffer.
delete[] pszOutBuffer;
// This condition should never be reached since WinHttpQueryDataAvailable
// reported that there are bits to read.
if (!dwDownloaded)
break;
} while (dwSize > 0);
}
if (response == "") {
wcout << "Value is blank: " << bResults << endl << GetLastError() << endl << response.c_str() << endl;
}
// Report any errors.
if (!bResults)
printf("Error %d has occurred.\n", GetLastError());
// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
return response;
编辑:同样使用curl lib也会产生不返回数据的相同结果(它将返回其他api上的数据)
编辑2:我也尝试过此示例中的解决方案WinHttpSendRequest失败并出现ERROR_WINHTTP_SECURE_FAILURE 它也无法获取数据,所以我不确定为什么它无法获取数据。
编辑 3:Fiddler 报告 HTTP/1.1 200 好 缓存控制:私有 内容长度:0 内容类型:文本/纯文本;字符集=UTF-8 服务器:微软-IIS/8.5 设置 Cookie:CFID=randomCookie;Path=/ 设置 Cookie:CFTOKEN=0;路径=/ 返回格式:普通 X-AspNet-版本:4.0.30319 X-Powered-By:ASP.NET 日期:2019 年 6 月 6 日星期四 18:15:01 GMT
我也遇到过同样的问题。 通过在命令提示符下执行“netsh winhttp重置代理”,问题解决了。