我有一个使用WinInet API时可以正常运行的请求。现在,我想用WinHTTP API发出该请求,因为我已经在项目中使用了它,而且它更好。我的请求用于调用JSON。在致电之前,我已经通过了身份验证。进行身份验证时,我会获取通过Cookie发送的SessionID。
所以这是我的WinInet代码:
DWORD dwError;
HINTERNET hOpen = NULL, hReq = NULL;
hOpen = InternetOpen(_T(""), INTERNET_OPEN_TYPE_DIRECT, _T(""), _T(""), 0);
if(hOpen == NULL)
{
dwError = GetLastError();
return false;
}
CString cstrCookies = _T("Cookie: JSESSIONID=") + cstrSession;
CString cstr = _T("https://") + cstrServer + _T("/list/") + cstrFileOrFolder;
hReq = InternetOpenUrl(hOpen, cstr, cstrCookies, -1L,
INTERNET_FLAG_SECURE | INTERNET_FLAG_NO_COOKIES, 0); // without NO_COOKIES I'll get a 401
if(hReq == NULL)
{
dwError = GetLastError();
InternetCloseHandle(hOpen);
return false;
}
DWORD dwCode, dwCodeSize;
dwCodeSize = sizeof(DWORD);
if(!HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwCode, &dwCodeSize, NULL))
{
dwError = GetLastError();
InternetCloseHandle(hReq);
InternetCloseHandle(hOpen);
return false;
}
InternetCloseHandle(hOpen);
InternetCloseHandle(hReq);
return dwCode == 200;
因此,我现在想使用WinHTTP API进行相同的操作。这是我目前所拥有的:
DWORD dwError = 0;
HINTERNET hConnect = NULL, hRequest = NULL;
hConnect = WinHttpConnect(m_hSession, cstrServer, INTERNET_DEFAULT_HTTPS_PORT, 0);
if (hConnect == NULL)
{
return false;
}
hRequest = WinHttpOpenRequest(hConnect, NULL, cstrMethod + _T("/list/") + cstrFileOrFolder,
NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (hRequest == NULL)
{
WinHttpCloseHandle(hConnect);
return false;
}
DWORD dwOptionValue = WINHTTP_DISABLE_COOKIES;
if (WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &dwOptionValue,
sizeof(dwOptionValue)) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
const CString cstrHeaders = _T("Cookie: JSESSIONID=") + cstrSession;
if (WinHttpAddRequestHeaders(hRequest, cstrHeaders, cstrHeaders.GetLength(),
WINHTTP_ADDREQ_FLAG_ADD) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
if (WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, -1L, WINHTTP_NO_REQUEST_DATA, 0,
0, 0) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
if (WinHttpReceiveResponse(hRequest, NULL) != TRUE)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
DWORD dwCode, dwCodeSize;
dwCodeSize = sizeof(DWORD);
if(!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwCode, &dwCodeSize, NULL))
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return false;
}
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return dwCode == 200;
对于后者,我总是收到401,但我应该像第一种方法一样得到200。我还发现,当我未指定
INTERNET_FLAG_NO_COOKIES
标志时,我会在第一次调用时收到401。因此,我怀疑Cookie标头中的内容有误。有人看到我在做什么错吗?或这两种方法有什么区别?谢谢...
最佳答案
看起来不错。
如果您是我,则可以连接一个HTTP调试代理(如Fiddler),并检查和比较这两种方法的HTTP流量。这可能会指出您需要执行的操作。