废话少说,直接上代码
//用字典来存储响应体
private Dictionary<ulong, List<byte>> requestList = new Dictionary<ulong, List<byte>>();
//先给ChromiumWebBrowser加上filter事件
WebBrowser.RequestHandler.GetResourceResponseFilter += RequestHandler_GetResourceResponseFilter;
//在ChromiumWebBrowser的资源加载完成后处理数据
WebBrowser.RequestHandler.OnResourceLoadComplete += (s, e) => {
if (requestList.ContainsKey(e.Request.Identifier))//判断键
{
string DataStr = Encoding.UTF8.GetString(requestList[e.Request.Identifier].ToArray());//响应内容转成string类型
//
//在这里处理数据
//
requestList.Remove(e.Request.Identifier);//处理完数据从字典里面移除这条数据
}
}
//filter事件
private void RequestHandler_GetResourceResponseFilter(object s, CfxGetResourceResponseFilterEventArgs e)
{
CfxResponseFilter responseFilter = new CfxResponseFilter();
ulong requestId = e.Request.Identifier;//请求id,用来做字典的键
string requestUrl = e.Request.Url;//请求url,可以用来做一些过滤
int totalWritten = 0;
this.requestList.Add(e.Request.Identifier, new List<byte>());
responseFilter.InitFilter += (s2, e2) => {
e2.SetReturnValue(true);
};
responseFilter.Filter += (s2, e2) => {
// 判断有没有数据要处理
if (e2.DataIn == IntPtr.Zero && e2.DataOut == IntPtr.Zero)
{
e2.SetReturnValue(CfxResponseFilterStatus.Done);
return;
}
// 将数据添加到字典里面去,当然你想直接在这里处理也可以
if (e2.DataIn != IntPtr.Zero && e2.DataInSize > 0)
{
byte[] inData = new byte[e2.DataInSize];
Marshal.Copy(e2.DataIn, inData, 0, (int)e2.DataInSize);
requestList[requestId].AddRange(inData);
e2.DataInRead = (UIntPtr)e2.DataInSize;
}
if (e2.DataOut != IntPtr.Zero && e2.DataOutSize > 0)
{
int dataOutLen = Math.Min((int)requestList[requestId].Count - totalWritten, (int)e2.DataOutSize);
Marshal.Copy(requestList[requestId].ToArray(), totalWritten, e2.DataOut, dataOutLen);
e2.DataOutWritten = (UIntPtr)dataOutLen;
totalWritten += dataOutLen;
}
e2.SetReturnValue(CfxResponseFilterStatus.NeedMoreData);
};
e.SetReturnValue(responseFilter);
}
完成,有不懂的地方欢迎留言,我看到就会回复
网友评论