cef 的http請求


文章目錄

    • 1.網絡層
      • 1.1 自定義請求
      • 1.2獨立於瀏覽器的請求
    • 2.請求處理
      • 2.1 通用資源管理器
      • 2.2 方案處理句柄
      • 2.3 請求攔截
      • 2.4 響應過濾
      • 2.5 其他回調
    • 3.代理解析
    • 4.作者答疑

 

1.網絡層

??默認情況下,CEF3 中的網絡請求將以對主機應用程序透明的方式處理。對於希望與網絡層建立更密切關系的應用程序,CEF3 公開了一系列與網絡相關的功能。與網絡相關的回調可能發生在不同的線程上,因此請務必注意文檔並正確保護您的數據成員。

1.1 自定義請求

??在瀏覽器框架中加載 URL 的最簡單方法是通過 CefFrame::LoadURL() 方法。

browser->GetMainFrame()->LoadURL(some_url); 

??希望發送包含自定義請求標頭或上傳數據的更復雜請求的應用程序可以使用 CefFrame::LoadRequest() 方法。此方法接受CefRequest對象作為單個參數。

// Create a CefRequest object. CefRefPtr<CefRequest> request = CefRequest::Create(); // Set the request URL. request->SetURL(some_url); // Set the request method. Supported methods include GET, POST, HEAD, DELETE and PUT. request->SetMethod(“POST”); // Optionally specify custom headers. CefRequest::HeaderMap headerMap; headerMap.insert(std::make_pair("X-My-Header", "My Header Value")); request->SetHeaderMap(headerMap); // Optionally specify upload content. // The default “Content-Type” header value is "application/x-www-form-urlencoded". // Set “Content-Type” via the HeaderMap if a different value is desired. const std::string& upload_data = “arg1=val1&arg2=val2”; CefRefPtr<CefPostData> postData = CefPostData::Create(); CefRefPtr<CefPostDataElement> element = CefPostDataElement::Create(); element->SetToBytes(upload_data.size(), upload_data.c_str()); postData->AddElement(element); request->SetPostData(postData); 

1.2獨立於瀏覽器的請求

??應用程序可以通過CefURLRequest類發送與特定瀏覽器無關的網絡請求。實現CefURLRequestClient接口來處理結果響應。CefURLRequest 可以在瀏覽器和渲染進程中使用。

class MyRequestClient : public CefURLRequestClient { public: MyRequestClient() : upload_total_(0), download_total_(0) {} void OnRequestComplete(CefRefPtr<CefURLRequest> request) OVERRIDE { CefURLRequest::Status status = request->GetRequestStatus(); CefURLRequest::ErrorCode error_code = request->GetRequestError(); CefRefPtr<CefResponse> response = request->GetResponse(); // Do something with the response... } void OnUploadProgress(CefRefPtr<CefURLRequest> request, int64 current, int64 total) OVERRIDE { upload_total_ = total; } void OnDownloadProgress(CefRefPtr<CefURLRequest> request, int64 current, int64 total) OVERRIDE { download_total_ = total; } void OnDownloadData(CefRefPtr<CefURLRequest> request, const void *data, size_t data_length) OVERRIDE { download_data_ += std::string(static_cast<const char *>(data), data_length); } bool GetAuthCredentials(bool isProxy, const CefString &host, int port, const CefString &realm, const CefString &scheme, CefRefPtr<CefAuthCallback> callback) OVERRIDE { return false; // Not handled. } private: int64 upload_total_; int64 download_total_; std::string download_data_; private: IMPLEMENT_REFCOUNTING(MyRequestClient); }; 

發送請求:

// Set up the CefRequest object. CefRefPtr<CefRequest> request = CefRequest::Create(); // Populate |request| as shown above... // Create the client instance. CefRefPtr<MyRequestClient> client = new MyRequestClient(); // Start the request. MyRequestClient callbacks will be executed asynchronously. CefRefPtr<CefURLRequest> url_request = CefURLRequest::Create(request, client.get(), nullptr); // To cancel the request: url_request->Cancel(); 

??使用 CefURLRequest 發出的請求還可以通過 CefRequest::SetFlags() 方法指定自定義行為。支持的位標志包括:

  • UR_FLAG_SKIP_CACHE如果設置,則在處理請求時將跳過緩存。
  • UR_FLAG_ALLOW_CACHED_CREDENTIALS如果設置 cookie 可以與請求一起發送並從響應中保存。還必須設置 UR_FLAG_ALLOW_CACHED_CREDENTIALS。
  • UR_FLAG_REPORT_UPLOAD_PROGRESS如果設置了當請求有正文時將生成上傳進度事件。
  • UR_FLAG_NO_DOWNLOAD_DATA如果設置 CefURLRequestClient::OnDownloadData 方法將不會被調用。
  • UR_FLAG_NO_RETRY_ON_5XX如果設置 5XX 重定向錯誤將傳播到觀察者而不是自動重試。這目前僅適用於源自瀏覽器進程的請求。

??例如,跳過緩存而不報告下載數據:

request->SetFlags(UR_FLAG_SKIP_CACHE | UR_FLAG_NO_DOWNLOAD_DATA); 

2.請求處理

??CEF3 支持兩種處理應用程序內部網絡請求的方法。方案處理程序方法允許為針對特定來源(方案 + 域)的請求注冊處理程序。請求攔截方法允許應用程序自行處理任意請求。使用 HTTP 方案而不是自定義方案來避免一系列潛在問題。
??如果您選擇使用自定義方案(除“HTTP”、“HTTPS”等之外的任何方案),您必須向 CEF 注冊它,以便它按預期運行。如果您希望自定義方案的行為類似於 HTTP(支持 POST 請求並強制執行HTTP 訪問控制 (CORS)限制),則應將其注冊為“標准”方案。如果您計划對其他方案執行跨域請求或通過 XMLHttpRequest 將 POST 請求發送到您的方案處理程序,那么您應該使用 HTTP 方案而不是自定義方案以避免潛在問題。如果您希望使用自定義方案,則通過必須在所有進程中實現的 CefApp::OnRegisterCustomSchemes() 回調注冊屬性。

void MyApp::OnRegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar) { // Register "client" as a standard scheme. registrar->AddCustomScheme("client", true, ...); } 

2.1 通用資源管理器

??CEF 提供了一種用於管理來自一個或多個數據源的資源請求的通用實現。此用戶為不同的數據源(例如磁盤上的目錄、zip 存檔或自定義實現)注冊處理程序,然后由管理器處理請求。應用程序通過向路由器傳遞來自標准 CEF C++ 回調(OnBeforeResourceLoad、GetResourceHandler)的數據與路由器交互。有關演示 CefResourceManager 用法的獨立示例應用程序,請參閱resource_manager 示例。有關完整的使用文檔,請參閱include/wrapper/cef_resource_manager.h。

2.2 方案處理句柄

??方案處理句柄通過 CefRegisterSchemeHandlerFactory() 函數注冊。調用這個函數的一個好地方是 CefBrowserProcessHandler::OnContextInitialized()。例如,您可以為“client://myapp/”請求注冊一個處理句柄:

CefRegisterSchemeHandlerFactory("client", “myapp”, new MySchemeHandlerFactory()); 

??處理程序可以與內置方案(HTTP、HTTPS 等)和自定義方案一起使用。使用內置方案時,請選擇您的應用程序獨有的域名(如“myapp”或“internal”)。實現CefSchemeHandlerFactory和CefResourceHandler類來處理請求並提供響應數據。如果使用自定義方案,請不要忘記實現上述 CefApp::OnRegisterCustomSchemes 方法。有關演示 CefSchemeHandlerFactory 用法的獨立示例應用程序,請參閱scheme_handler 示例。有關完整的使用文檔,請參閱include/cef_scheme.h。

??如果在請求時響應數據是已知的,CefStreamResourceHandler類提供了一個方便的 CefResourceHandler 的默認實現。

// CefStreamResourceHandler is part of the libcef_dll_wrapper project. #include “include/wrapper/cef_stream_resource_handler.h” const std::string &html_content = “<html><body>Hello! < / body > < / html > ”; // Create a stream reader for |html_content|. CefRefPtr<CefStreamReader> stream = CefStreamReader::CreateForData( static_cast<void *>(const_cast<char *>(html_content.c_str())), html_content.size()); // Constructor for HTTP status code 200 and no custom response headers. // There’s also a version of the constructor for custom status code and response headers. return new CefStreamResourceHandler("text/html", stream); 

2.3 請求攔截

??CefRequestHandler::GetResourceHandler() 方法支持攔截任意請求。它使用與方案處理程序方法相同的 CefResourceHandler 類。如果使用自定義方案,請不要忘記實現上述 CefApp::OnRegisterCustomSchemes 方法。

CefRefPtr<CefResourceHandler> MyHandler::GetResourceHandler( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request) { // Evaluate |request| to determine proper handling... if (...) return new MyResourceHandler(); // Return NULL for default handling of the request. return NULL; } 

2.4 響應過濾

??CefRequestHandler::GetResourceResponseFilter() 方法支持過濾請求響應數據。有關工作示例,請參見cefclient/browser/response_filter_test.cc(可通過測試菜單 > 其他測試 > 響應過濾從 cefclient 示例應用程序內部訪問)。

2.5 其他回調

??該CefRequestHandler接口提供了各種網絡相關的事件incuding驗證,cookie處理,外部協議處理,證書錯誤等回調。

3.代理解析

??代理設置在 CEF3 中使用與 Google Chrome 相同的命令行標志進行配置。

--proxy-server=host:port Specify the HTTP/SOCKS4/SOCKS5 proxy server to use for requests. An individual proxy server is specified using the format: [<proxy-scheme>://]<proxy-host>[:<proxy-port>] Where <proxy-scheme> is the protocol of the proxy server, and is one of: "http", "socks", "socks4", "socks5". If the <proxy-scheme> is omitted, it defaults to "http". Also note that "socks" is equivalent to "socks5". Examples: --proxy-server="foopy:99" Use the HTTP proxy "foopy:99" to load all URLs. --proxy-server="socks://foobar:1080" Use the SOCKS v5 proxy "foobar:1080" to load all URLs. --proxy-server="sock4://foobar:1080" Use the SOCKS v4 proxy "foobar:1080" to load all URLs. --proxy-server="socks5://foobar:66" Use the SOCKS v5 proxy "foobar:66" to load all URLs. It is also possible to specify a separate proxy server for different URL types, by prefixing the proxy server specifier with a URL specifier: Example: --proxy-server="https=proxy1:80;http=socks4://baz:1080" Load https://* URLs using the HTTP proxy "proxy1:80". And load http://* URLs using the SOCKS v4 proxy "baz:1080". --no-proxy-server Disables the proxy server. --proxy-auto-detect Autodetect proxy configuration. --proxy-pac-url=URL Specify proxy autoconfiguration URL. 

??如果代理需要身份驗證,CefRequestHandler::GetAuthCredentials() 回調將使用 |isProxy| 執行。值為 true 以檢索用戶名和密碼。

bool MyHandler::GetAuthCredentials( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, bool isProxy, const CefString &host, int port, const CefString &realm, const CefString &scheme, CefRefPtr<CefAuthCallback> callback) { if (isProxy) { // Provide credentials for the proxy server connection. callback->Continue("myuser", "mypass"); return true; } return false; } 

??由於網絡代理解析(例如,如果在 Windows 上選中“自動檢測代理設置”),應用程序啟動期間的 Web 內容加載可能會延遲。為了獲得最佳用戶體驗,請考慮將您的應用程序設計為首先顯示靜態啟動頁面,然后使用元刷新重定向到實際網站——重定向將被阻止,直到代理解析完成。出於測試目的,可以使用“–no-proxy-server”命令行標志禁用代理解析。通過從命令行運行“chrome --url=…”,也可以在 Google Chrome 中復制代理解析延遲。

 

轉載於:libcef-框架架構中概念介紹-網絡層(請求)-請求處理-請求攔截-代理解析(六) (betheme.net)

CEF3:https 請求返回狀態碼canceled_李四老師的博客-CSDN博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM