【发布时间】:2013-12-01 22:24:16
【问题描述】:
我正在尝试使用 VC++ 2008 在 WM 6.5 上获取 URL 的内容,而不是超级小玩意
CString http_request(CString params){
CInternetSession session(_T("My Session")); // add device identifier here?
CHttpConnection* pServer = NULL;
CHttpFile* pFile = NULL;
CString szHeaders( _T("Content-Type: application/x-www-form-urlencoded;Accept: text/xml, text/plain, text/html, text/htm\r\nHost: www.mydomain.com\r\n\r\n"));
CString strObject("");
CString out;
DWORD dwRet;
char *szBuff = new char[1023];
try
{
CString strServerName("www.mydomain.com");
INTERNET_PORT nPort(80);
pServer = session.GetHttpConnection(strServerName, nPort);
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
pFile->AddRequestHeaders(szHeaders);
pFile->SendRequest(LPCTSTR(params),params.GetLength());
pFile->QueryInfoStatusCode(dwRet);
if (dwRet == HTTP_STATUS_OK)
{
UINT nRead = pFile->Read(szBuff, 1023);
while (nRead > 0)
{
//read file...
out = CString(szBuff);
}
}
delete pFile;
delete pServer;
}
catch (CInternetException* pEx)
{
//catch errors from WinInet
out = CString("Something went wrong.");
}
session.Close();
return out;
}
我确实看到了请求,但 URI 没有通过,因此服务器抛出 500 或 404。
我尝试将参数传递为“GET /blah.txt HTTP/1.0”和“/blah.txt”,没有运气,想继续测试各种输入参数,但设备由于某种原因挂起......
任何指针将不胜感激!
TIA
稍后编辑:解决方案:
这是我如何让它工作的完整代码 sn-p,以防有人想要复制粘贴解决方案(是的,这些很方便)
CString http_request(CString server, CString uri){
CInternetSession session(_T("My Session")); // add device identifier here? IMEI ftw
CHttpConnection* pServer = NULL;
CHttpFile* pFile = NULL;
CString szHeaders( _T("Content-Type: application/x-www-form-urlencoded;Accept: text/xml, text/plain, text/html, text/htm\r\nHost: www.domain.com\r\n\r\n")); // maybe pass as param?
CString strObject(uri);
CString out;
DWORD dwRet;
CString params;
char *szBuff = new char[1023];
try
{
CString strServerName(server);
INTERNET_PORT nPort(80);
pServer = session.GetHttpConnection(strServerName, nPort);
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
pFile->AddRequestHeaders(szHeaders);
pFile->SendRequest(szHeaders, szHeaders.GetLength(),¶ms, params.GetLength());
pFile->QueryInfoStatusCode(dwRet);
if (dwRet == HTTP_STATUS_OK)
{
UINT nRead = pFile->Read(szBuff, 1023);
//while (nRead > 0)
//{
//read, for more data you might want to uncomment the while and append to a var. I only needed a few bytes actually.
out = CString(szBuff);
//}
} else {
out = CString("Communication error!");
}
delete pFile;
delete pServer;
}
catch (CInternetException* pEx)
{
//catch errors from WinInet
out = CString("Network error!"); // stupid a$$ cpp the code to handle this would be longer than my ****
}
session.Close();
pServer->Close();
return out;
}
【问题讨论】:
-
您的 strObject 为空。这不应该是你放“blah.txt”的地方吗?请在您的问题中添加您传递给此函数的参数。
-
做到了!不得不以一些奇怪的不寻常的方式弄乱参数(最初尝试传递 CString 没有运气)。这对我来说很奇怪,我来自 Linux 背景。再次非常感谢您的评论!也许您可以将其发布为答案,我现在将使用解决方案更新问题。
标签: visual-c++ windows-mobile windows-mobile-6.5