使用 CefSharp 捕获资源响应数据(正文)

Using CefSharp to capture Resource Response Data (body)

我正在尝试使用 CefSharp 访问 URL 并捕获在加载给定页面期间检索到的特定资源。大概是每个资源的流或字节数组。

CefSharp 提供接口IRequestHandler。您可以创建一个 class 实现此接口以响应 Request/Response 事件,但它不以任何方式包含响应主体。

IRequestHandler 的实现中查看 GetResourceResponseFilterGetResourceResponseFilter returns 和 IResponseFilter,这让您有机会收集所有回复。您需要实现自己的 IResponseFilter,谢天谢地有大量示例。

Example IResponseFilter 实现取自 CefSharp GitHub 项目。

public class MemoryStreamResponseFilter : IResponseFilter
{
        private MemoryStream memoryStream;

        bool IResponseFilter.InitFilter()
        {
            //NOTE: We could initialize this earlier, just one possible use of InitFilter
            memoryStream = new MemoryStream();
             
            return true;
        }

        FilterStatus IResponseFilter.Filter(Stream dataIn, out long dataInRead, Stream dataOut, out long dataOutWritten)
        {
            if (dataIn == null)
            {
                dataInRead = 0;
                dataOutWritten = 0;

                return FilterStatus.Done;
            }

            dataInRead = dataIn.Length;
            dataOutWritten = Math.Min(dataInRead, dataOut.Length);

            //Important we copy dataIn to dataOut
            dataIn.CopyTo(dataOut);

            //Copy data to stream
            dataIn.Position = 0;
            dataIn.CopyTo(memoryStream);

            return FilterStatus.Done;
        }

        void IDisposable.Dispose()
        {
            memoryStream.Dispose();
            memoryStream = null;
        }

        public byte[] Data
        {
            get { return memoryStream.ToArray(); }
        }
    }

现在在您的 GetResourceResponseFilter 方法中:

 private Dictionary<ulong, MemoryStreamResponseFilter> responseDictionary = new Dictionary<ulong, MemoryStreamResponseFilter>();
 public IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
 {
       var dataFilter = new MemoryStreamResponseFilter();
       responseDictionary.Add(request.Identifier, dataFilter);
       return dataFilter;
 }

然后在 OnResourceLoadComplete:

public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
{      
    MemoryStreamResponseFilter filter;
    if (responseDictionary.TryGetValue(request.Identifier, out filter))
    {
        var data = filter.Data; //This returns a byte[]
        //File.WriteAllBytes("c:/save/path", data);
    }
}

您可以使用 IRequestIResponse 参数中的属性来决定要过滤的内容。