You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinHttpCrackUrl解析HTTPS时nScheme错误显示为Other(2)原因排查

问题描述

运行以下C代码后,输出的协议类型并非HTTPS,而是Other(2)。执行环境为Windows 10(64位),代码以C14标准编译,请问该问题产生的原因是什么?

#include <windows.h>
#include <WinInet.h>
#include <winhttp.h>
#include <iostream>
#include <string>

#pragma comment(lib, "wininet.lib")
#pragma comment(lib, "Winhttp.lib")

int main() {
    std::wstring gitHubApiUrl = L"https://api.github.com";

    URL_COMPONENTSW urlComponents = {};
    urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);

    // Buffers for host and path
    wchar_t hostName[256] = {};
    wchar_t urlPath[1024] = {};
    urlComponents.lpszHostName = hostName;
    urlComponents.dwHostNameLength = ARRAYSIZE(hostName);
    urlComponents.lpszUrlPath = urlPath;
    urlComponents.dwUrlPathLength = ARRAYSIZE(urlPath);

    // Call WinHttpCrackUrl
    if (!WinHttpCrackUrl(gitHubApiUrl.c_str(), static_cast<DWORD>(gitHubApiUrl.size()), 0, &urlComponents)) {
        std::wcerr << L"Failed to parse URL. Error: " << GetLastError() << std::endl;
        return 0;
    }

    // Output parsed components
    std::wcout << L"Scheme: ";
    switch (urlComponents.nScheme) {
    case INTERNET_SCHEME_HTTP: std::wcout << L"HTTP"; break;
    case INTERNET_SCHEME_HTTPS: std::wcout << L"HTTPS"; break;
    default: std::wcout << L"Other (" << urlComponents.nScheme << L")"; break;
    }
    std::wcout << std::endl;

    std::wcout << L"Host Name: " << urlComponents.lpszHostName << std::endl;
    std::wcout << L"URL Path: " << urlComponents.lpszUrlPath << std::endl;
    return 0;
}
问题原因及解决方案
  • 核心原因:代码混用了WinINet和WinHTTP两个库的协议枚举常量。INTERNET_SCHEME_HTTP、INTERNET_SCHEME_HTTPS是WinINet库定义的枚举值,但WinHttpCrackUrl属于WinHTTP库,它返回的nScheme对应的是WinHTTP的枚举常量,两者数值不匹配:
    • WinINet中INTERNET_SCHEME_HTTPS的值为3
    • WinHTTP中HTTPS对应的枚举是WINHTTP_SCHEME_HTTPS,数值为2
  • 修复方案:将switch语句中的枚举替换为WinHTTP库的对应常量:
    switch (urlComponents.nScheme) {
    case WINHTTP_SCHEME_HTTP: std::wcout << L"HTTP"; break;
    case WINHTTP_SCHEME_HTTPS: std::wcout << L"HTTPS"; break;
    default: std::wcout << L"Other (" << urlComponents.nScheme << L")"; break;
    }
    
  • 注意事项:WinINet和WinHTTP是Windows平台独立的网络API,枚举、结构体与函数不能跨库混用,使用某一库的函数时必须配套使用该库的相关常量和类型。

内容的提问来源于stack exchange,提问作者MrHu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:23:16