以编程方式与网络进行通信不是我的专业领域,但我设法通过从在线示例中剪切和粘贴代码来创建 read_web_page() 函数,并且该代码已经连续好几个月每天正常工作。
碰巧我工作时的主 Windows-10 电脑坏了,在等待维修时,我现在被迫在家里的 Windows-7 电脑上运行(相同的)代码。
但是现在我出现了一个我以前从未见过的错误。我调用以下代码(简化):
// code to handle bad return values from the following three functions ommitted...
HINTERNET hsession = WinHttpOpen(0,WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS, 0);
HINTERNET hconnect = WinHttpConnect(hsession, (LPCWSTR)thewebsite, INTERNET_DEFAULT_HTTPS_PORT , 0);
HINTERNET hrequest = WinHttpOpenRequest(hconnect, L"GET", (LPCWSTR)thesubdirectory, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!WinHttpSendRequest(hrequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
{
int err = GetLastError();
通常 WinHttpSendRequest 返回零,但现在返回非零值,并且 GetLastError() 返回值 12175(等于 ERROR_WINHTTP_SECURE_FAILURE)。
我连接的 (https) URL 始终相同,当我将其输入浏览器时,该网站仍然正常显示。
也许电脑和位置的整个变化是巧合,问题是由我正在阅读的网站的幕后变化引起的(它不在我的控制之下)......但我不知道如何开始诊断(或修复)故障。这可能与我的 ISP 有关吗?
documentation for WinHttpSendRequest说可以通过设置回调函数找到此错误的更详细信息,但描述如何完成此操作的文档对我来说是无法理解的,而且我在任何地方都找不到任何示例代码。
编辑:为了解决 Barmak 对网站和子目录的担忧,创建它们的代码如下:
char *char_thewebsite = "www.thewebsite.com";
char *char_thesubdirectory = "sub";
int n_website = MultiByteToWideChar(CP_ACP, 0, char_thewebsite, -1, NULL, 0);
int n_subdir = MultiByteToWideChar(CP_ACP, 0, char_thesubdirectory, -1, NULL, 0);
thewebsite = new WCHAR[n_website];
thesubdirectory = new WCHAR[n_subdir];
MultiByteToWideChar(CP_ACP, 0, char_thewebsite, -1, (LPWSTR)thewebsite, n_website);
MultiByteToWideChar(CP_ACP, 0, char_thesubdirectory, -1, (LPWSTR)thesubdirectory, n_subdir);
最佳答案
这是一个很长的评论,不是答案!
WinINet 更简单,如果不需要 WinHTTP 服务器功能,可以使用 WinINet 库。但是,您不能同时使用 WinINet 和 WinHTTP。
声明字符串时,最好从 UTF-16 字符串开始 wchar_t *str = L"str"
。有时您的源字符串采用 UTF-8 格式,在这种情况下,您可以使用 MultiByteToWideChar(CP_UTF8...)
转换为 UTF-16。
WinINet 示例:
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <WinINet.h>
#pragma comment(lib, "WinINet.lib")
int main()
{
const wchar_t* url = L"https://stackoverflow.com/questions";
std::ofstream fout(L"c:\\test\\test.htm");
HINTERNET hopen = InternetOpen(L"MyAppName",
INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(hopen)
{
DWORD flags = INTERNET_FLAG_DONT_CACHE;
if(wcsstr(url, L"https://") == url)
flags |= INTERNET_FLAG_SECURE;
HINTERNET hinternet = InternetOpenUrl(hopen, url, NULL, 0, flags, 0);
if(hinternet)
{
char buf[1024];
DWORD received = 0;
while(InternetReadFile(hinternet, buf, sizeof(buf), &received))
{
if(!received) break;
fout.write(buf, received);
}
std::cout << "success!\n";
InternetCloseHandle(hinternet);
}
InternetCloseHandle(hopen);
}
return 0;
}
关于c - WinHttpSendRequest 失败并显示 ERROR_WINHTTP_SECURE_FAILURE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47554388/