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

问题描述 投票:0回答:2

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

CefSharp提供了IRequestHandler接口。您可以创建一个实现此接口的类来响应请求/响应事件,但它不以任何方式包含响应主体。

cefsharp
2个回答
9
投票

查看

GetResourceResponseFilter
的实现中的
IRequestHandler
GetResourceResponseFilter
返回
IResponseFilter
,它为您提供了捕获所有响应的机会。您需要实现自己的
IResponseFilter
,幸运的是有足够的示例。

示例

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);
    }
}

您可以使用

IRequest
IResponse
参数中的属性来决定要过滤的内容。


© www.soinside.com 2019 - 2024. All rights reserved.