2017-08-18 110 views
0

我想從託管C++中的應用程序登錄到我的網站。我正在使用curl來做到這一點,儘管我沒有收到任何錯誤,但我很困惑如何獲取檢查登錄是否成功所需的信息。不幸的是,我找不到有類似問題的人,所以我很感激任何幫助。用CURL(C++)登錄論壇

private: System::Void bLogin_Click (System::Object^ sender, System::EventArgs^ e) 
{ 
    if (System::String::IsNullOrEmpty (tbUsername->Text)) 
    { 
     System::String^ str = gcnew System::String ("Login failed! Please enter a valid username."); 
     System::Windows::Forms::MessageBox::Show (str); 

     return; 
    } 
    if (System::String::IsNullOrEmpty (tbUsername->Text)) 
    { 
     System::String^ str = gcnew System::String ("Login failed! Please enter a valid password"); 
     System::Windows::Forms::MessageBox::Show (str); 

     return; 
    } 

    using System::Runtime::InteropServices::Marshal; 

    curl_global_init (CURL_GLOBAL_ALL); 

    CURL* curl = curl_easy_init(); 
    if (!curl) 
    { 
     curl_global_cleanup(); 
     return; 
    } 

    curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 1L); 
    curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 1L); 

    curl_easy_setopt (curl, CURLOPT_USERAGENT, "Mozilla/4.0"); 
    curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1); 
    curl_easy_setopt (curl, CURLOPT_URL, "https://www.myurl.com/member.php?action=login"); 

    const char* szUser = static_cast< const char* >(Marshal::StringToHGlobalAnsi (tbUsername->Text).ToPointer()); 
    const char* szPass = static_cast< const char* >(Marshal::StringToHGlobalAnsi (tbPassword->Text).ToPointer()); 


    curl_easy_setopt (curl, CURLOPT_POST, 1L); 
    curl_easy_setopt (curl, CURLOPT_POSTFIELDS, Fmt::Fmt ("username=%s&password=%s", szUser, szPass)); 
    //curl_easy_setopt (curl, CURLOPT_USERPWD, Fmt::Fmt ("%s:%s", szUser, szPass)); 

    std::string strData; 
    curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, WriteCallback); 
    curl_easy_setopt (curl, CURLOPT_WRITEDATA, &strData); 


    CURLcode res = curl_easy_perform (curl); 
    /* its always CURLE_OK */ 
    if (res != CURLE_OK) 
    { 
     System::Windows::Forms::MessageBox::Show ("A error has occured during the login process."); 
    } 

    Marshal::FreeHGlobal (System::IntPtr (reinterpret_cast< long long >(szUser))); 
    Marshal::FreeHGlobal (System::IntPtr (reinterpret_cast< long long >(szPass))); 

    /* check if suceeded here... but everything in strData is the same whether the credentials are right or wrong */ 


    curl_easy_cleanup (curl); 
    curl_global_cleanup(); 
} 

此外,我的網站附帶「通配符SSL」,但我不確定這是否重要? 我對所有這些都很陌生,所以我很抱歉如果我做錯了什麼。

+0

看起來不像C++給我。像'System :: String^str = something','^'字符是一個算術運算符,並且應該會讓你的編譯器拋出一個語法錯誤,我想... – hanshenrik

+0

它是託管的C++ – Mike

回答

0

區分成功登錄和失敗登錄完全取決於服務器提供的答覆。由於我們不知道涉及什麼Web應用程序,因此我們無法提供更精確的信息。其次,使用來自託管C++項目的curl很奇怪。您可以訪問提供易於使用的HTTP客戶端的.NET框架,避免所有手動清理/編組。

+0

非常感謝。我切換到使用WebRequest類,然後添加了「do_login」參數,然後檢查結果是否包含「登錄」。它現在工作完美!再次感謝 – Mike

0

我最終使用WebRequest類,正如D. Jurcau建議的那樣。此外,我添加action=do_login到params,然後檢查字符串,如果它成功