CEF框架:各种各样的Handle(四)——CefURLRequest,发起HTTP请求与处理

本文主要是介绍CEF框架:各种各样的Handle(四)——CefURLRequest,发起HTTP请求与处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • CEF的HTTP请求类
    • CefResourceRequest
    • CefURLRequest
  • CefURLRequest的使用
    • cef_message_route
    • handled:urlrequet的处理类
      • OnQuery
  • CefURLRequestClient

CEF的HTTP请求类

在CEF框架中(Chromium Embedded Framework),CefURLRequestCefResourceRequest确实是两个不同的功能类,它们的主要区别在于使用场景和功能:

CefResourceRequest

  • 这个类通常用于加载资源类型的请求,比如在渲染网页时加载HTML文件、脚本、样式表、图片等。
  • CefResourceRequest主要用于内部处理浏览器的渲染操作,例如当浏览器需要获取并显示一个页面上的资源时。
  • 它通常不会直接暴露给通过CEF构建应用程序的开发者,除非开发者打算实现自定义的资源加载逻辑。
  • 简单的说,这个类用于控制在浏览器渲染时使用,发起和结束都不是程序来控制,只是说可以获得其中的过程数据进行处理,在上一篇CEF框架:各种各样的Handle(三)——拦截Http的请求与响应中已经有详细的说明。

CefURLRequest

  • CefURLRequest是一个更通用的请求类,它可以用于任何类型的HTTP请求,包括异步的和非阻塞的网络访问。
  • 开发者可以使用这个类来执行自定义的HTTP请求,如下载文件、提交表单数据、访问RESTful API等。
  • 它提供了一组回调接口(CefURLRequestClient),使开发者可以对请求过程中的各种事件作出响应,如开始请求、完成请求、错误发生、数据可用等。
  • 也就是说,当服务器需要自己来发起HTTP请求的时候,比如要发起GET,POST,DELETE等请求的时候,就可以使用CefURLRequest来发起。

CefURLRequest的使用

在CEF的框架示例代码中,cefclient就给出了如何使用CefURLRequest类的例子:

这个代码在resource/urlrequest.html文件中,这个文件中关键的代码就是这个按钮,也就是发起http请求的代码:

function execURLRequest() {document.getElementById('ta').value = 'Request pending...';// Results in a call to the OnQuery method in urlrequest_test.cppwindow.cefQuery({request: 'URLRequestTest:' + document.getElementById("url").value,onSuccess: function(response) {document.getElementById('ta').value = response;},onFailure: function(error_code, error_message) {document.getElementById('ta').value = 'Failed with error ' + error_message + ' (' + error_code + ')';}});
}

可以看到,就是调用了CEF框架中封装的cefQuery函数,详情在最早的一篇CEF文章中就提到过:CEF消息传递实战(实测可用,新鲜出炉)。

cef_message_route

在CEF消息传递实战(实测可用,新鲜出炉)中也提到了,是需要定义一个Handler来处理前端JS调用的cefQuery请求的。在CEF的框架示例代码CEFSIMPLE中,可以新定义一个Handler来处理。

在CEFCLIENT中,定义了一个消息的路由中心,这个路由器在cef_message_route文件中:

  • 统一的消息处理类

    class CefMessageRouterBrowserSideImpl : public CefMessageRouterBrowserSide
    {...bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefProcessId source_process,CefRefPtr<CefProcessMessage> message) OVERRIDE {CEF_REQUIRE_UI_THREAD();const std::string& message_name = message->GetName();if (message_name == query_message_name_) {CefRefPtr<CefListValue> args = message->GetArgumentList();DCHECK_EQ(args->GetSize(), 4U);const int context_id = args->GetInt(0);const int request_id = args->GetInt(1);const CefString& request = args->GetString(2);const bool persistent = args->GetBool(3);if (handler_set_.empty()) {// No handlers so cancel the query.CancelUnhandledQuery(browser, frame, context_id, request_id);return true;}const int browser_id = browser->GetIdentifier();const int64 query_id = query_id_generator_.GetNextId();CefRefPtr<CallbackImpl> callback(new CallbackImpl(this, browser_id, query_id, persistent));// Make a copy of the handler list in case the user adds or removes a// handler while we're iterating.HandlerSet handler_set = handler_set_;bool handled = false;HandlerSet::const_iterator it_handler = handler_set.begin();for (; it_handler != handler_set.end(); ++it_handler) {handled = (*it_handler)->OnQuery(browser, frame, query_id, request, persistent,callback.get());if (handled)break;}// If the query isn't handled nothing should be keeping a reference to// the callback.DCHECK(handled || callback->HasOneRef());if (handled) {// Persist the query information until the callback executes.// It's safe to do this here because the callback will execute// asynchronously.QueryInfo* info = new QueryInfo;info->browser = browser;info->frame = frame;info->context_id = context_id;info->request_id = request_id;info->persistent = persistent;info->callback = callback;info->handler = *(it_handler);browser_query_info_map_.Add(browser_id, query_id, info);} else {// Invalidate the callback.callback->Detach();// No one chose to handle the query so cancel it.CancelUnhandledQuery(browser, frame, context_id, request_id);}return true;} else if (message_name == cancel_message_name_) {CefRefPtr<CefListValue> args = message->GetArgumentList();DCHECK_EQ(args->GetSize(), 2U);const int browser_id = browser->GetIdentifier();const int context_id = args->GetInt(0);const int request_id = args->GetInt(1);CancelPendingRequest(browser_id, context_id, request_id);return true;}return false;}...
    }
    

    这段代码中通过Handler调用具体的处理类,handled = (*it_handler) ->OnQuery(browser, frame, query_id, request, persistent, callback.get());

handled:urlrequet的处理类

urlrequet的处理类定义在urlrequest_test.cc类中:

// Handle messages in the browser process. Only accessed on the UI thread.
class Handler : public CefMessageRouterBrowserSide::Handler {public:Handler() { CEF_REQUIRE_UI_THREAD(); }~Handler() { CancelPendingRequest(); }// Called due to cefQuery execution in urlrequest.html.bool OnQuery(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,int64 query_id,const CefString& request,bool persistent,CefRefPtr<Callback> callback) OVERRIDE {CEF_REQUIRE_UI_THREAD();// Only handle messages from the test URL.const std::string& url = frame->GetURL();if (!test_runner::IsTestURL(url, kTestUrlPath))return false;const std::string& message_name = request;if (message_name.find(kTestMessageName) == 0) {const std::string& load_url =message_name.substr(sizeof(kTestMessageName));CancelPendingRequest();DCHECK(!callback_.get());DCHECK(!urlrequest_.get());callback_ = callback;// Create a CefRequest for the specified URL.CefRefPtr<CefRequest> cef_request = CefRequest::Create();cef_request->SetURL(load_url);cef_request->SetMethod("GET");// Callback to be executed on request completion.// It's safe to use base::Unretained() here because there is only one// RequestClient pending at any given time and we explicitly detach the// callback in the Handler destructor.const RequestClient::Callback& request_callback =base::Bind(&Handler::OnRequestComplete, base::Unretained(this));// Create and start a new CefURLRequest associated with the frame, so// that it shares authentication with ClientHandler::GetAuthCredentials.urlrequest_ = frame->CreateURLRequest(cef_request, new RequestClient(request_callback));return true;}return false;}private:// Cancel the currently pending URL request, if any.void CancelPendingRequest() {CEF_REQUIRE_UI_THREAD();if (urlrequest_.get()) {// Don't execute the callback when we explicitly cancel the request.static_cast<RequestClient*>(urlrequest_->GetClient().get())->Detach();urlrequest_->Cancel();urlrequest_ = nullptr;}if (callback_.get()) {// Must always execute |callback_| before deleting it.callback_->Failure(ERR_ABORTED, test_runner::GetErrorString(ERR_ABORTED));callback_ = nullptr;}}void OnRequestComplete(CefURLRequest::ErrorCode error_code,const std::string& download_data) {CEF_REQUIRE_UI_THREAD();if (error_code == ERR_NONE)callback_->Success(download_data);elsecallback_->Failure(error_code, test_runner::GetErrorString(error_code));callback_ = nullptr;urlrequest_ = nullptr;}CefRefPtr<Callback> callback_;CefRefPtr<CefURLRequest> urlrequest_;DISALLOW_COPY_AND_ASSIGN(Handler);
};

OnQuery

这个函数就是响应html文件中的JS事件的响应函数。

  • const std::string& load_url = message_name.substr(sizeof(kTestMessageName)); 过滤掉filter的关键字,留下HTTP请求的url地址。

  • 创建http请求

    // Create a CefRequest for the specified URL.
    CefRefPtr<CefRequest> cef_request = CefRequest::Create();
    cef_request->SetURL(load_url);
    cef_request->SetMethod("GET");
    
  • 提交http请求

    urlrequest_ = frame->CreateURLRequest(cef_request, new RequestClient(request_callback));
    

    简单来说,就是把这个request请求提交到对应的服务端了。

  • 再创建一个callback(一个函数指针),这个callback不是cef框架到JS界面的callback,而是urlrequest类相关的,处理整个http请求各关键事件的callback。

    // Callback to be executed on request completion.
    // It's safe to use base::Unretained() here because there is only one
    // RequestClient pending at any given time and we explicitly detach the
    // callback in the Handler destructor.
    const RequestClient::Callback& request_callback =base::Bind(&Handler::OnRequestComplete, base::Unretained(this));
    
  • OnRequestComplete,也就是当requst请求得到响应后,CEF框架就会调用这个函数,在上面的代码中可以看到,就是调用了callback_方法(这个callback就是记录了JS的匿名方法了),把对应的download_data返回到前端显示。

CefURLRequestClient

前面提到的都是从JS到CEF框架,然后再到消息路由,最后到某种消息的处理HANDLE,而这个消息HANDLE中最后才调用到整个URLREQUEST的框架HANDLE:CefURLRequestClient,定义在cef_urlrequest.h中。

class CefURLRequestClient : public virtual CefBaseRefCounted {public:virtual void OnRequestComplete(CefRefPtr<CefURLRequest> request) = 0;virtual void OnUploadProgress(CefRefPtr<CefURLRequest> request,int64 current,int64 total) = 0;virtual void OnDownloadProgress(CefRefPtr<CefURLRequest> request,int64 current,int64 total) = 0;virtual void OnDownloadData(CefRefPtr<CefURLRequest> request,const void* data,size_t data_length) = 0;virtual bool GetAuthCredentials(bool isProxy,const CefString& host,int port,const CefString& realm,const CefString& scheme,CefRefPtr<CefAuthCallback> callback) = 0;
};

为了节省篇幅,我将这个类中的所有注释全部去掉了,这个类就是定义了在HTTP请求的整个过程中,几个关键事件的钩子函数,这个几个函数都是纯虚函数,所以需要完成URLREQUEST的使用的话,自定义一个类对这个几个函数都需要重定义。

在CEF的示例中,代码为:

class RequestClient : public CefURLRequestClient {public:// Callback to be executed on request completion.typedef base::Callback<void(CefURLRequest::ErrorCode /*error_code*/,const std::string& /*download_data*/)>Callback;explicit RequestClient(const Callback& callback) : callback_(callback) {CEF_REQUIRE_UI_THREAD();DCHECK(!callback_.is_null());}void Detach() {CEF_REQUIRE_UI_THREAD();if (!callback_.is_null())callback_.Reset();}void OnRequestComplete(CefRefPtr<CefURLRequest> request) OVERRIDE {CEF_REQUIRE_UI_THREAD();if (!callback_.is_null()) {callback_.Run(request->GetRequestError(), download_data_);callback_.Reset();}}void OnUploadProgress(CefRefPtr<CefURLRequest> request,int64 current,int64 total) OVERRIDE {}void OnDownloadProgress(CefRefPtr<CefURLRequest> request,int64 current,int64 total) OVERRIDE {}void OnDownloadData(CefRefPtr<CefURLRequest> request,const void* data,size_t data_length) OVERRIDE {CEF_REQUIRE_UI_THREAD();download_data_ += std::string(static_cast<const char*>(data), data_length);std::cout << download_data_ << std::endl;}bool GetAuthCredentials(bool isProxy,const CefString& host,int port,const CefString& realm,const CefString& scheme,CefRefPtr<CefAuthCallback> callback) OVERRIDE {return false;}private:Callback callback_;std::string download_data_;IMPLEMENT_REFCOUNTING(RequestClient);DISALLOW_COPY_AND_ASSIGN(RequestClient);
};

几个纯虚函数的具体作用,可以参考cef_urlrequest.h中的注释,而且从名字也很容易判断出来,也就是CEF框架对这种通过的URL请求提供了这些自定义能力。

在这个示例中,主要就是通过定义OnDownloadData方法,来将所有的下载到的内容放到download_data_字符串中(CEF每次下载的大小由trunk大小来控制)。

这篇关于CEF框架:各种各样的Handle(四)——CefURLRequest,发起HTTP请求与处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1009232

相关文章

SpringBoot请求参数接收控制指南分享

《SpringBoot请求参数接收控制指南分享》:本文主要介绍SpringBoot请求参数接收控制指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring Boot 请求参数接收控制指南1. 概述2. 有注解时参数接收方式对比3. 无注解时接收参数默认位置

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Spring 请求之传递 JSON 数据的操作方法

《Spring请求之传递JSON数据的操作方法》JSON就是一种数据格式,有自己的格式和语法,使用文本表示一个对象或数组的信息,因此JSON本质是字符串,主要负责在不同的语言中数据传递和交换,这... 目录jsON 概念JSON 语法JSON 的语法JSON 的两种结构JSON 字符串和 Java 对象互转

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

Java Response返回值的最佳处理方案

《JavaResponse返回值的最佳处理方案》在开发Web应用程序时,我们经常需要通过HTTP请求从服务器获取响应数据,这些数据可以是JSON、XML、甚至是文件,本篇文章将详细解析Java中处理... 目录摘要概述核心问题:关键技术点:源码解析示例 1:使用HttpURLConnection获取Resp

Java中Switch Case多个条件处理方法举例

《Java中SwitchCase多个条件处理方法举例》Java中switch语句用于根据变量值执行不同代码块,适用于多个条件的处理,:本文主要介绍Java中SwitchCase多个条件处理的相... 目录前言基本语法处理多个条件示例1:合并相同代码的多个case示例2:通过字符串合并多个case进阶用法使用

Java实现优雅日期处理的方案详解

《Java实现优雅日期处理的方案详解》在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间,下面我们就来看看如何使用java处理这样的日期问题吧,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言一、日期的坑1.1 日期格式化陷阱1.2 时区转换二、优雅方案的进阶之路2.1 线程安全重构2

Python处理函数调用超时的四种方法

《Python处理函数调用超时的四种方法》在实际开发过程中,我们可能会遇到一些场景,需要对函数的执行时间进行限制,例如,当一个函数执行时间过长时,可能会导致程序卡顿、资源占用过高,因此,在某些情况下,... 目录前言func-timeout1. 安装 func-timeout2. 基本用法自定义进程subp

Java字符串处理全解析(String、StringBuilder与StringBuffer)

《Java字符串处理全解析(String、StringBuilder与StringBuffer)》:本文主要介绍Java字符串处理全解析(String、StringBuilder与StringBu... 目录Java字符串处理全解析:String、StringBuilder与StringBuffer一、St