DWORD CLoginDlg::userProfile(LPCTSTR serverURL, LPCTSTR requestPage) { #ifdef _HTTPS CInternetSession session(_T("HelloChat"), INTERNET_FLAG_SECURE); CHttpConnection* pConnection = session.GetHttpConnection(serverURL, INTERNET_SERVICE_HTTP, INTERNET_DEFAULT_HTTPS_PORT); CString strToken = L"token:"; strToken = strToken + m_strMyToken + L"\r\n"; CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_NO_COOKIES); #else CInternetSession session(_T("HelloChat"), PRE_CONFIG_INTERNET_ACCESS); CHttpConnection* pConnection = session.GetHttpConnection(serverURL); CString strToken = L"token:"; //strToken = strToken + m_strToken + L"\r\n"; strToken = strToken + m_strMyToken + L"\r\n"; CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, requestPage, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_NO_COOKIES); #endif VERIFY(pFile->AddRequestHeaders(HEADER)); VERIFY(pFile->AddRequestHeaders(strToken)); VERIFY(pFile->SendRequest()); // GET POST STATUS DWORD dwPostStatus = 0; VERIFY(pFile->QueryInfoStatusCode(dwPostStatus)); CString strBuffer = L""; BOOL brtn = pFile->ReadString(strBuffer); char* rtnBuffer = LPSTR(LPCTSTR(strBuffer)); if (dwPostStatus == HTTP_STATUS_OK) { BOOL bRtn = dataParser(rtnBuffer); if (!bRtn){ AfxMessageBox(L"User Info Paser Error"); } } else{ CComm func; func.WriteErrorLog(rtnBuffer); } pFile->Close(); return dwPostStatus; }
BOOL CMainFrame::DonwLoadFile(PSTR pURL, LPSTR SaveAsFilePath) { CInternetSession session; CHttpConnection* pServer = NULL; CHttpFile * pHttpFile = NULL; CString strServerName; //去掉http:// CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; DWORD dwHttpRequestFlags = INTERNET_FLAG_NO_AUTO_REDIRECT; //请求标志 const TCHAR szHeaders[]=_T("Accept: text/*\r\nUser-Agent:HttpClient\r\n"); BOOL OK=AfxParseURL( pURL, dwServiceType, strServerName, strObject, nPort ); pServer = session.GetHttpConnection(strServerName, nPort); //获得服务器名 pHttpFile = pServer-> OpenRequest( CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pHttpFile->AddRequestHeaders(szHeaders); try { pHttpFile->SendRequest(); //发送请求 } catch (CInternetException* IE) { return false; } CStdioFile f; if( !f.Open( SaveAsFilePath, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary ) ) { return false; } TCHAR szBuf[1024]; int length=0; long a=pHttpFile->GetLength(); while (length=pHttpFile->Read(szBuf, 1023)) f.Write(szBuf,length); f.Close(); pHttpFile ->Close(); pServer ->Close(); if (pHttpFile != NULL) delete pHttpFile; if (pServer != NULL) delete pServer; session.Close(); return true; }
void CHttpPostDlg::OnBtnSendpost() { CInternetSession m_InetSession(_T("session"), 0, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_DONT_CACHE); //设置不缓冲 CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; CString strHtml = ""; CString ActionServer = _T("www.cqjg.gov.cn"); CString strRequest = _T("LicenseTxt=AG8091&VIN=LJDAAA21560205432"); //POST过去的数据 CString strHeaders = "Accept: text*/*\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon;"; int nRead = 0; try { INTERNET_PORT nPort = 80; //端口 pServer = m_InetSession.GetHttpConnection(ActionServer, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,"/netcar/FindOne.aspx"); pFile->AddRequestHeaders(strHeaders); pFile->SendRequestEx(strRequest.GetLength()); pFile->WriteString(strRequest); //重要-->m_Request 中有"name=aaa&name2=BBB&..." pFile->EndRequest(); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); if (dwRet == HTTP_STATUS_OK) { CString strLine; while ((nRead = pFile->ReadString(strLine))>0) { strHtml += strLine + "\n";; } } int pos = strHtml.Find(_T("<li class=\"lithreeC\">")); if(pos != -1) { CString Value = strHtml.Mid(pos,500); CFile file("test.html",CFile::modeCreate|CFile::modeWrite); file.WriteHuge(Value.GetBuffer(0),Value.GetLength()); file.Close(); //MessageBox(Value); } delete pFile; delete pServer; } catch (CInternetException* e) { char strErrorBuf[255]; e->GetErrorMessage(strErrorBuf,255,NULL); AfxMessageBox(strErrorBuf,MB_ICONINFORMATION); } // SendPost(); }
CString GetPageDirect(CString rAddress) { CString szResult; DWORD dwRet = 0; // HTTP返回码 CString strServerName, strObject; DWORD dwSvrType; INTERNET_PORT nPort; const TCHAR szHeaders[] = _T("Accept: text/*\r\nUser-Agent: CInternetThread\r\n"); AfxParseURL(rAddress, dwSvrType, strServerName, strObject, nPort); CInternetSession session("MySessionDirect"); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; try { pServer = session.GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet < 400) { char szBuff[1024]; UINT nRead = pFile->Read(szBuff, 1023); while (nRead > 0) { szBuff[nRead] = '\0'; szResult.Append(szBuff); nRead = pFile->Read(szBuff, 1023); } } delete pFile; delete pServer; } catch (CInternetException* pEx) { //uiResult = 0; } session.Close(); return szResult; }
int main(int argc, char* argv[]) { ShowBanner(); if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { cerr << _T("MFC Failed to initialize.\n"); return 1; } if (argc < 2 || !ParseOptions(argc, argv) || pszURL == NULL) ShowUsage(); int nRetCode = 0; CTearSession session(_T("TEAR - MFC Sample App"), dwAccessType); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; try { // check to see if this is a reasonable URL CString strServerName; CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; if (!AfxParseURL(pszURL, dwServiceType, strServerName, strObject, nPort) || dwServiceType != INTERNET_SERVICE_HTTP) { cerr << _T("Error: can only use URLs beginning with http://") << endl; ThrowTearException(1); } if (bProgressMode) { cerr << _T("Opening Internet..."); VERIFY(session.EnableStatusCallback(TRUE)); } pServer = session.GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); // if access was denied, prompt the user for the password if (dwRet == HTTP_STATUS_DENIED) { DWORD dwPrompt; dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); // if the user cancelled the dialog, bail out if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) { cerr << _T("Access denied: Invalid password\n"); ThrowTearException(1); } pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); } CString strNewLocation; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); // were we redirected? // these response status codes come from WININET.H if (dwRet == HTTP_STATUS_MOVED || dwRet == HTTP_STATUS_REDIRECT || dwRet == HTTP_STATUS_REDIRECT_METHOD) { CString strNewLocation; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); int nPlace = strNewLocation.Find(_T("Location: ")); if (nPlace == -1) { cerr << _T("Error: Site redirects with no new location") << endl; ThrowTearException(2); } strNewLocation = strNewLocation.Mid(nPlace + 10); nPlace = strNewLocation.Find('\n'); if (nPlace > 0) strNewLocation = strNewLocation.Left(nPlace); // close up the redirected site pFile->Close(); delete pFile; pServer->Close(); delete pServer; if (bProgressMode) { cerr << _T("Caution: redirected to "); cerr << (LPCTSTR) strNewLocation << endl; } // figure out what the old place was if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort)) { cerr << _T("Error: the redirected URL could not be parsed.") << endl; ThrowTearException(2); } if (dwServiceType != INTERNET_SERVICE_HTTP) { cerr << _T("Error: the redirected URL does not reference a HTTP resource.") << endl; ThrowTearException(2); } // try again at the new location pServer = session.GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet != HTTP_STATUS_OK) { cerr << _T("Error: Got status code ") << dwRet << endl; ThrowTearException(2); } } cerr << _T("Status Code is ") << dwRet << endl; TCHAR sz[1024]; while (pFile->ReadString(sz, 1023)) { if (bStripMode) StripTags(sz); cout << sz; } // NOTE: Since HTTP servers normally spit back plain text, the // above code (which reads line by line) is just fine. However, // other data sources (eg, FTP servers) might provide binary data // which should be handled a buffer at a time, like this: #if 0 while (nRead > 0) { sz[nRead] = '\0'; if (bStripMode) StripTags(sz); cout << sz; nRead = pFile->Read(sz, 1023); } #endif pFile->Close(); pServer->Close(); } catch (CInternetException* pEx) { // catch errors from WinINet TCHAR szErr[1024]; pEx->GetErrorMessage(szErr, 1024); cerr << _T("Error: (") << pEx->m_dwError << _T(") "); cerr << szErr << endl; nRetCode = 2; pEx->Delete(); } catch (CTearException* pEx) { // catch things wrong with parameters, etc nRetCode = pEx->m_nErrorCode; TRACE1("Error: Exiting with CTearException(%d)\n", nRetCode); pEx->Delete(); } if (pFile != NULL) delete pFile; if (pServer != NULL) delete pServer; session.Close(); return nRetCode; }
HRESULT CMainFrame::GetWMEVersionHttp(CString& WMEVersion) { HRESULT RetCode = S_OK; WMEVersion = "0.0.0"; CString Magic = GetRegString(HKEY_CURRENT_USER, DCGF_TOOLS_REG_PATH, "BBID"); CInternetSession Session; CHttpConnection* Server = NULL; CHttpFile* File = NULL; DWORD HttpRequestFlags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT; const TCHAR Headers[] = _T("Accept: text/*\r\nUser-Agent: WME ProjectMan\r\n"); CString Url = LOC("/str1086/http://www.dead-code.org/vercheck.php"); CString CurrVer; CurrVer.Format("%d.%d.%03d", DCGF_VER_MAJOR, DCGF_VER_MINOR, DCGF_VER_BUILD); Url += "?product=wme&ver=" + CurrVer; Url += "&bbid=" + Magic; if(DCGF_VER_BETA) Url += "&beta=1"; bool DotNet = RegKeyExists(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\.NETFramework\\policy\\v2.0"); Url += "&dotnet=" + CString(DotNet?"1":"0"); CString ServerName; CString Object; INTERNET_PORT Port; DWORD ServiceType; try{ if(!AfxParseURL(Url, ServiceType, ServerName, Object, Port) || ServiceType != INTERNET_SERVICE_HTTP){ return E_FAIL; } Server = Session.GetHttpConnection(ServerName, Port); File = Server->OpenRequest(CHttpConnection::HTTP_VERB_GET, Object, NULL, 1, NULL, NULL, HttpRequestFlags); File->AddRequestHeaders(Headers); if(File->SendRequest()){ TCHAR sz[1024]; if(File->ReadString(sz, 1023)){ WMEVersion = Entry(1, CString(sz), '\n'); } } File->Close(); Server->Close(); } catch (CInternetException* pEx) { // catch errors from WinINet //TCHAR szErr[1024]; //pEx->GetErrorMessage(szErr, 1024); //MessageBox(szErr, LOC("/str1002/Error"), MB_OK|MB_ICONERROR); RetCode = E_FAIL; pEx->Delete(); } if (File != NULL) delete File; if (Server != NULL) delete Server; Session.Close(); return RetCode; }
//Lets get the file via http DWORD CMyInternetSession::GetWebFile(LPCTSTR pstrAgent, LPCTSTR lpstrServer, int nPort,CString strPathName) { static unsigned short usFileName = 1; //Check what file types we will allow to be requested CString extension = strPathName.Right(3); //get filename CString strFName; int sym = strPathName.ReverseFind('/'); if(sym != 0) { int len = strPathName.GetLength(); strFName = strPathName.Right(len-sym-1); } else strFName = strPathName; if(extension == "exe") { return 0; } if(extension == "com") { return 0; } if (extension == "dll") { return 0; } if (extension == "bat") { return 0; } if (extension == "sys") { return 0; } if (extension == "inf") { return 0; } DWORD dwAccessType = PRE_CONFIG_INTERNET_ACCESS; DWORD dwHttpRequestFlags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_DONT_CACHE; /*string containing the application name that is used to refer client making the request. If this NULL the frame work will call the global function AfxGetAppName which returns the application name.*/ //LPCTSTR pstrAgent = NULL; //the verb we will be using for this connection //if NULL then GET is assumed LPCTSTR pstrVerb = "GET"; //the address of the url in the request was obtained from LPCTSTR pstrReferer = NULL; //Http version we are using; NULL = HTTP/1.0 LPCTSTR pstrVersion = NULL; //For the Accept request headers if we need them later on //LPCTSTR pstrAcceptTypes = "Accept: audio/x-aiff, audio/basic, audio/midi, audio/mpeg, audio/wav, image/jpeg, image/gif, image/jpg, image/png, image/mng, image/bmp, text/plain, text/html, text/htm\r\n"; LPCTSTR pstrAcceptTypes = NULL; CString szHeaders = "Accept: audio/x-aiff, audio/basic, audio/midi, audio/mpeg, audio/wav, image/jpeg, image/gif, image/jpg, image/png, image/mng, image/bmp, text/plain, text/html, text/htm\r\n"; //the server port we need changed //nPort = INTERNET_INVALID_PORT_NUMBER unsigned short usPort = nPort; //Username we will use if a secure site comes into play LPCTSTR pstrUserName = NULL; //The password we will use LPCTSTR pstrPassword = NULL; //CInternetSession flags if we need them //DWORD dwFlags = INTERNET_FLAG_ASYNC; DWORD dwFlags = NULL; //Proxy setting if we need them LPCTSTR pstrProxyName = NULL; LPCTSTR pstrProxyBypass = NULL; CMyInternetSession session(pstrAgent, dwAccessType, pstrProxyName, pstrProxyBypass, dwFlags); //Set any CInternetSession options we may need int ntimeOut = 30; session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT,1000* ntimeOut); session.SetOption(INTERNET_OPTION_CONNECT_BACKOFF,1000); session.SetOption(INTERNET_OPTION_CONNECT_RETRIES,1); //Enable or disable status callbacks session.EnableStatusCallback(TRUE); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; DWORD dwRet; try { pServer = session.GetHttpConnection(lpstrServer, usPort, pstrUserName, pstrPassword); pFile = pServer->OpenRequest(pstrVerb, strPathName, pstrReferer, 1, &pstrAcceptTypes, pstrVersion, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->AddRequestHeaders("User-Agent: GetWebFile/1.0\r\n", HTTP_ADDREQ_FLAG_ADD_IF_NEW); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet);//Check wininet.h for info //about the status codes if (dwRet == HTTP_STATUS_DENIED) { return dwRet; } if (dwRet == HTTP_STATUS_MOVED || dwRet == HTTP_STATUS_REDIRECT || dwRet == HTTP_STATUS_REDIRECT_METHOD) { CString strNewAddress; //again check wininet.h for info on the query info codes //there is alot one can do and re-act to based on these codes pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewAddress); int nPos = strNewAddress.Find(_T("Location: ")); if (nPos == -1) { return 0; } strNewAddress = strNewAddress.Mid(nPos + 10); nPos = strNewAddress.Find('\n'); if (nPos > 0) strNewAddress = strNewAddress.Left(nPos); pFile->Close(); delete pFile; pServer->Close(); delete pServer; CString strServerName; CString strObject; INTERNET_PORT nNewPort; DWORD dwServiceType; if (!AfxParseURL(strNewAddress, dwServiceType, strServerName, strObject, nNewPort)) { return 0; } pServer = session.GetHttpConnection(strServerName, nNewPort, pstrUserName, pstrPassword); pFile = pServer->OpenRequest(pstrVerb, strObject, pstrReferer, 1, &pstrAcceptTypes, pstrVersion, dwHttpRequestFlags); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet != HTTP_STATUS_OK) { return dwRet; } } if(dwRet == HTTP_STATUS_OK) { int len = pFile->GetLength(); char buf[2000]; int numread; CString filepath; filepath.Format("%s\\%03d.djvu",m_strDownloadDirectory,usFileName); CFile myfile(filepath, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary); while ((numread = pFile->Read(buf,sizeof(buf)-1)) > 0) { buf[numread] = '\0'; strFName += buf; myfile.Write(buf, numread); } myfile.Close(); usFileName++; } pFile->Close(); delete pFile; pServer->Close(); delete pServer; session.Close(); } catch (CInternetException* pEx) { // catch any exceptions from WinINet TCHAR szErr[1024]; szErr[0] = '\0'; if(!pEx->GetErrorMessage(szErr, 1024)) strcpy(szErr,"Some crazy unknown error"); TRACE("File transfer failed!! - %s",szErr); pEx->Delete(); if(pFile) delete pFile; if(pServer) delete pServer; session.Close(); return 0; } return dwRet; }
BOOL http_command(char *url, char *cmd, int timeout, char *uid, char *pwd, char *pserver, int pport, char *puid, char *ppwd, char *szReturn) { BOOL bResult = TRUE; CString strCmdInfo = _T(""); CString strRemoteUrl = _T(""); CInternetSession *psession = NULL; CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; if(*pserver) { char pbuff[256] = {0}; sprintf(pbuff, "%s:%d", pserver, pport); psession = new CInternetSession("WinInet", 1, INTERNET_OPEN_TYPE_PROXY, pbuff, NULL, 0); } else { psession = new CInternetSession("WinInet"); } try { CString strServerName; CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; strCmdInfo.Format("echo %s;%s;echo %s", C_STA, cmd, C_END); strCmdInfo.Replace(' ', '+'); strRemoteUrl.Format("%s?%s", url, strCmdInfo); if (!AfxParseURL(strRemoteUrl, dwServiceType, strServerName, strObject, nPort) || dwServiceType != INTERNET_SERVICE_HTTP) { sprintf(szReturn, "%s", FuncGetStringFromIDS("<%IDS_Utils_1%>"));//<%IDS_Utils_1%> return FALSE; } pServer = psession->GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT); if(*puid) { CString User_Pass = _T(""); User_Pass.Format("%s:%s", puid, ppwd); CString strOutput = _T("Proxy-Authorization: Basic "); CBase64 *pBase64 = new CBase64(); strOutput.Insert(strOutput.GetLength(), pBase64->Encode(User_Pass, User_Pass.GetLength())); delete pBase64; pBase64 = NULL; pFile->AddRequestHeaders(strOutput); } pFile->SendRequest(); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); if(dwRet == HTTP_STATUS_DENIED) { CString User_Pass = _T(""); User_Pass.Insert(User_Pass.GetLength(), uid); User_Pass.Insert(User_Pass.GetLength(), ':'); User_Pass.Insert(User_Pass.GetLength(), pwd); CString strOutput = _T("Authorization: Basic "); CBase64 *pBase64 = new CBase64(); strOutput.Insert(strOutput.GetLength(), pBase64->Encode(User_Pass, User_Pass.GetLength())); delete pBase64; pBase64 = NULL; pFile->AddRequestHeaders(strOutput); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); } if(dwRet == 200) { while(1) { char *ca = NULL, *cb = NULL; char buf[8192] = {0}; int n = pFile->Read(buf, sizeof(buf)); if(n == 0) break; buf[n] = 0; strncat(szReturn, buf, n); if(ca = strstr(szReturn, C_STA)) { if(cb = strstr(szReturn, C_END)) { ca += strlen(C_STA); while(*ca == 0x0A || *ca == 0x0D) ca ++; while(*cb == 0x0A || *cb == 0x0D) cb ++; strncpy(szReturn, ca, cb - ca); szReturn[cb - ca] = 0; break; } } } } else { sprintf(szReturn, "%ld", dwRet); bResult = FALSE; } if(pFile) pFile->Close(); if(pServer) pServer->Close(); } catch (CInternetException* pEx) { TCHAR szErr[1024]; pEx->GetErrorMessage(szErr, 1024); sprintf(szReturn, "%s", szErr); bResult = FALSE; pEx->Delete(); } if (pFile != NULL) delete pFile; if (pServer != NULL) delete pServer; psession->Close(); delete psession; return bResult; }
void CHttpClient::DoOpenURL( LPCTSTR lpszURL, DWORD dwHttpRequestFlags, CString &strHeader, CString &strPostData, CInternetSession *pSession, CHttpConnection **ppServer, CHttpFile **ppFile, PROGRESS_CALLBACK fnCallback, void * cookie ) { CString strServerName; CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; int nVerb = (strPostData.GetLength()>0 ? CHttpConnection::HTTP_VERB_POST : CHttpConnection::HTTP_VERB_GET); if (!AfxParseURL(lpszURL, dwServiceType, strServerName, strObject, nPort) || dwServiceType != INTERNET_SERVICE_HTTP) { ThrowTearException( ERR_TEAR_URLFORMAT ); } if( fnCallback ) fnCallback( PROG_HTTPCONNECTTING, 0, NULL, cookie ); CHttpConnection *pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd ); CHttpFile * pFile = pServer->OpenRequest(nVerb, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE); if( strPostData.GetLength() > 0 ) // post { try { pFile->SendRequestEx( DWORD(strPostData.GetLength()) ); pFile->WriteString(strPostData); pFile->EndRequest(); } catch( CInternetException *pp ) // HTTP_STATUS_BAD_METHOD { pp->Delete(); // close up the redirected site pFile->Close(); delete pFile; pFile = NULL; pServer->Close(); delete pServer; pServer = NULL; pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd ); pFile = pServer->OpenRequest(nVerb, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE); pFile->SendRequestEx( DWORD(strPostData.GetLength()) ); pFile->WriteString(strPostData); pFile->EndRequest(); } } else { pFile->SendRequest(); } if( fnCallback ) fnCallback( PROG_REQUESTSENT, 0, NULL, cookie ); // Bad Post method DWORD dwRet = 0; pFile->QueryInfoStatusCode( dwRet ); // if access was denied, prompt the user for the password if (dwRet == HTTP_STATUS_DENIED || dwRet == HTTP_STATUS_PROXY_AUTH_REQ ) { DWORD dwPrompt; dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); // if the user cancelled the dialog, bail out if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) ThrowTearException( ERR_TEAR_CANCEL ); if( strPostData.GetLength() > 0 ) // post { try{ pFile->SendRequestEx( DWORD(strPostData.GetLength()) ); pFile->WriteString(strPostData); pFile->EndRequest(); } catch( CInternetException *pp ) // HTTP_STATUS_BAD_METHOD { pp->Delete(); pFile->SendRequestEx( DWORD(strPostData.GetLength()) ); pFile->WriteString(strPostData); pFile->EndRequest(); } } else { pFile->SendRequest(); } pFile->QueryInfoStatusCode(dwRet); } if( dwRet == HTTP_STATUS_BAD_METHOD ) { // close up the redirected site pFile->Close(); delete pFile; pFile = NULL; pServer->Close(); delete pServer; pServer = NULL; pServer = pSession->GetHttpConnection(strServerName, dwHttpRequestFlags, nPort, m_strProxyUser, m_strProxyPasswd ); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->AddRequestHeaders(strHeader, HTTP_ADDREQ_FLAG_COALESCE); if( strPostData.GetLength() > 0 ) // post { pFile->SendRequestEx( DWORD(strPostData.GetLength()) ); pFile->WriteString(strPostData); pFile->EndRequest(); } else { pFile->SendRequest(); } } *ppServer = pServer; *ppFile = pFile; }
int CHttpRequest::ConnectUrl(TCHAR *sUrl, TCHAR *sReturn, long *lVersion, int *Count) { ODS(_T("XFILTER.EXE: GetFromUrl Begin... \n")); if(sUrl == NULL) return XERR_INVALID_PARAMETER; CString strServerName; CString strObject; INTERNET_PORT nPort; DWORD dwServiceType; if (!AfxParseURL(sUrl, dwServiceType, strServerName, strObject, nPort) || dwServiceType != INTERNET_SERVICE_HTTP) { ODS(_T("XFILTER.EXE: Internet Invalid Url ...")); return XERR_INTERNET_URL_ERROR; } CInternetSession session(GUI_APP_CLASS_NAME); CHttpConnection *pServer = NULL; CHttpFile *pFile = NULL; int iRet = XERR_SUCCESS; m_IsConnecting = TRUE; try { pServer = session.GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); if (dwRet >= 400 && dwRet <= 499) { ODS(_T("XFILTER.EXE: Internet Request Error ...")); iRet = XERR_INTERNET_REQUEST_ERROR; } else if(dwRet >= 500 && dwRet <= 599) { ODS(_T("XFILTER.EXE: Internet Server Error ...")); iRet = XERR_INTERNET_SERVER_ERROR; } else if(sReturn != NULL) { pFile->ReadString(sReturn, MAX_NET_COMMAND_LENTH - 1); ODS(sReturn); CString tmpStr = sReturn; long lVer = atol(tmpStr.Left(MAX_NET_COMMAND_VERSION_LENTH)); if(lVer > *lVersion) { *lVersion = lVer; int i = 1; while (i < MAX_NET_COMMAND && pFile->ReadString((sReturn + MAX_NET_COMMAND_LENTH * i), MAX_NET_COMMAND_LENTH - 1)) { ODS(sReturn + i * MAX_NET_COMMAND_LENTH); i ++; } *Count = i; } else { *Count = 1; } } else { CString sRet; pFile->ReadString(sRet); if(sRet.GetAt(0) != '1') iRet = XERR_INTERNET_REG_ERROR; ODS2(_T("XFILTER.EXE: Internet User Register Return Value "),sRet); } pFile->Close(); pServer->Close(); } catch(CInternetException* pEx) { pEx->Delete(); iRet = XERR_INTERNET_CONNECT_ERROR; ODS(_T("XFILTER.EXE: GetFromUrl XERR_INTERNET_CONNECT_ERROR... ")); } if (pFile != NULL) delete pFile; if (pServer != NULL) delete pServer; session.Close(); m_IsConnecting = FALSE; ODS(_T("XFILTER.EXE: GetFromUrl End... ")); return iRet; }
ERMsg DownloadStation(CHttpConnectionPtr& pConnection, const std::string& ID, int year, std::string& text) { ERMsg msg; CString URL = _T("010-001/archive.aspx"); CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded\r\n");//\r\nUser-Agent: HttpCall\r\n CStringA strParam = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKLTk1NTAxMjAxMA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YoBAtXQ7YoBAtXQ6YoBApTRytAPApTR5rkJApTR0twBAv%2Fo4MUGAv%2Fo3JgNAv%2FoyL8EAv%2FopNIMAv%2FokOkLAv%2FojIwCAvKEiO4EAvS6t0wC9bq3TAL2urdMAve6t0wC8Lq3TALxurdMAvK6t0wC47q3TALsurdMAvS6908C9Lr7TwL0uv9PAvS6w08C9LrHTwL0ustPAvS6z08C9LrTTwL0updMAvS6m0wC9br3TwL1uvtPAvW6%2F08C9brDTwL1usdPAvW6y08C9brPTwL1utNPAvW6l0wC9bqbTAL2uvdPAva6%2B08C14iy%2BgQC1oiy%2BgQC1Yiy%2BgQC1Iiy%2BgQC04iy%2BgQC0oiy%2BgQC0Yiy%2BgQCwIiy%2BgQCz4iy%2BgQC14jy%2BQQC14j%2B%2BQQC14j6%2BQQCrte4hQQCrteU7AICrtegiQoCxe6SkA0Cxe6uzQYCxe666g8Cxe7WhwcCxe7iPALF7v7ZCQL0x6SlAQKA3uC2A0LNcpbYprj4QvUiSHNkEUzsHvnf&ctl00%24hfLang=fr-CA&"; strParam += ("ctl00%24Content1%24ddlWS=" + ID).c_str(); strParam += "&ctl00%24Content1%24ddlFromDay=1"; strParam += "&ctl00%24Content1%24ddlFromMonth=1"; strParam += ("&ctl00%24Content1%24ddlFromYear=" + ToString(year)).c_str(); strParam += "&ctl00%24Content1%24hdnFromDate="; strParam += "&ctl00%24Content1%24ddlToDay=31" ; strParam += "&ctl00%24Content1%24ddlToMonth=12"; strParam += ("&ctl00%24Content1%24ddlToYear=" + ToString(year)).c_str(); strParam += "&ctl00%24Content1%24hdnToDate=&ctl00%24Content1%24btnGetData=Submit"; DWORD HttpRequestFlags = INTERNET_FLAG_EXISTING_CONNECT |INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE; CHttpFile* pURLFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, URL, NULL, 1, NULL, NULL, HttpRequestFlags); bool bRep = false; if (pURLFile != NULL) { int nbTry = 0; while (!bRep && msg) { TRY { nbTry++; pURLFile->AddRequestHeaders(strHeaders); CString strContentL; strContentL.Format(_T("Content-Length: %d\r\n"), strParam.GetLength()); pURLFile->AddRequestHeaders(strContentL); // send request bRep = pURLFile->SendRequest(0, 0, (void*)(const char*)strParam, strParam.GetLength()) != 0; } CATCH_ALL(e) { DWORD errnum = GetLastError(); if (errnum == 12002 || errnum == 12029) { if (nbTry >= 10) { msg = UtilWin::SYGetMessage(*e); } //try again } else if (errnum == 12031 || errnum == 12111) { //throw a exception: server reset THROW(new CInternetException(errnum)); } else if (errnum == 12003) { msg = UtilWin::SYGetMessage(*e); DWORD size = 255; TCHAR cause[256] = { 0 }; InternetGetLastResponseInfo(&errnum, cause, &size); if (_tcslen(cause) > 0) msg.ajoute(UtilWin::ToUTF8(cause)); } else { CInternetException e(errnum); msg += UtilWin::SYGetMessage(e); } } END_CATCH_ALL } }
/// <summary> /// Uploads a temporarily stored image to imgur. /// </summary> /// <returns>Direct link to the image if succeess, empty string otherwise</returns> std::string Uploader::imgur() { FILE *fp; // File pointer unsigned char *buffer; // our buffer, a buffer of BYTE[] long fileLen; // Just the file length in bytes. // Convert the CStringW to a char* for fopen CString absPath = this->getTempFile(); const size_t __path = (absPath.GetLength() + 1) * 2; char *absPathChar = new char[__path]; size_t convertedCharsw = 0; wcstombs_s(&convertedCharsw, absPathChar, __path, absPath, _TRUNCATE); // Open the file in binary mode fp = fopen(absPathChar, "rb"); if(!fp) { AfxMessageBox(_T("Failed to open the screenshot file.")); return _EMPTY; } fseek(fp, 0, SEEK_END); // Jump to the end of the file fileLen = ftell(fp); // Get the size rewind(fp); // Jump back to the beginning of the file // Allocate memory buffer = (unsigned char *)malloc((fileLen)*sizeof(unsigned char)); if(!buffer) { AfxMessageBox(_T("Failed to allocate memory.")); return _EMPTY; } fread(buffer, fileLen, 1, fp); // Read in the entire file fclose(fp); // Close CStringA Dest = this->ToBase64(buffer, fileLen); // Base64 encode // Now construct an HTTP request. CString requestHeaders = _T("Content-Type: application/x-www-form-urlencoded\r\nAuthorization: Client-ID 3c1a6553ba0bbe4"); // Cast it to a CStringA which can then be used to convert to a char * CStringA postData("image=" + Dest); // Convert to char* otherwise the server drops requests, time_wasted = ~10 hours. const size_t newsizea = (postData.GetLength() + 1); char *postDataChar = new char[newsizea]; strcpy_s(postDataChar, newsizea, postData); // Spawn a session here CInternetSession session(NULL, 1, PRE_CONFIG_INTERNET_ACCESS, NULL, NULL, 0); if(!session) return _EMPTY; // Look up for 10 seconds session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10000); session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3); INTERNET_PORT port = 443; // We are demanded to use HTTPS so // Open up the connection CHttpConnection *pConnection = session.GetHttpConnection(_T("api.imgur.com"), port); // Some self-explanatory flags. DWORD dwRequestFlags = INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_SECURE | INTERNET_DEFAULT_HTTPS_PORT; // Open up a connection CHttpFile *pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T("/3/image.xml"), NULL, 1, NULL, NULL, dwRequestFlags); pFile->AddRequestHeaders(requestHeaders); // Send the request BOOL result = pFile->SendRequest(requestHeaders, (LPVOID)postDataChar, strlen(postDataChar)); DWORD retCode; pFile->QueryInfoStatusCode(retCode); if(retCode != HTTP_STATUS_OK) { // API Failed AfxMessageBox(_T("API did not return 200 OK. Request failed.")); delete[] postDataChar;free(buffer); return _EMPTY; } // Grab the request now char *szBuff = new char[1024]; pFile->Read(szBuff, 1024); // Check out if it's empty or not if(!szBuff) { AfxMessageBox(_T("Failed to retrieve a response.")); delete []postDataChar;delete []szBuff;free(buffer); return _EMPTY; } // Construct this into a std string std::string response(szBuff); response = InBetween(response, "<link>", "</link>"); // Grab the direct link. // Cleanup delete[] szBuff; delete[] postDataChar; pFile->Close(); delete pFile; delete pConnection; free(buffer); session.Close(); return response; }