如何在Tauri(含Wry)中拦截并读取Webview的网络请求?
在Wry中拦截Webview网络调用并读取HTTP请求
Wry提供了两个核心API来实现网络拦截与请求读取:on_resource_request(拦截所有资源请求)和protocol_handler(处理自定义协议请求),以下是具体实现方式:
1. 拦截并读取所有HTTP/HTTPS请求
使用on_resource_request回调,Webview发起任何资源请求(页面、API、静态资源等)时都会触发该回调,你可以从中获取请求的方法、URL、Headers、Body等完整信息。
代码示例
use wry::{ application::window::WindowBuilder, webview::{WebViewBuilder, ResourceRequest, ResourceResponse}, }; fn main() -> wry::Result<()> { let window = WindowBuilder::new() .with_title("Network Intercept Demo") .build()?; let _webview = WebViewBuilder::new(window)? .on_resource_request(|request: &ResourceRequest| { // 打印请求核心信息 println!("请求方法: {}", request.method()); println!("请求URL: {}", request.url()); println!("请求Headers: {:?}", request.headers()); // 读取并打印请求Body(仅针对POST/PUT等带Body的请求) if let Some(body_bytes) = request.body() { match String::from_utf8(body_bytes.to_vec()) { Ok(body_str) => println!("请求Body: {}", body_str), Err(e) => println!("Body解析失败: {}", e), } } // 允许请求继续执行,也可返回自定义响应中断原请求 ResourceResponse::Continue }) .with_url("https://your-web-app-url.com")? .build()?; wry::application::run::run_event_loop()?; Ok(()) }
2. 拦截并自定义处理特定网络调用
如果需要拦截特定URL或替换请求响应,可以在on_resource_request中添加URL判断逻辑,返回自定义的ResourceResponse;若要处理自定义协议(如myapp://),则使用protocol_handler。
拦截特定API并返回自定义响应
.on_resource_request(|request: &ResourceRequest| { let target_url = "https://your-api-url.com/data"; if request.url() == target_url { // 构造自定义响应 let custom_response = ResourceResponse::new( 200, vec![("Content-Type".to_string(), "application/json".to_string())], r#"{"data": "custom intercepted response"}"#.as_bytes().to_vec(), ); ResourceResponse::Response(custom_response) } else { // 其他请求正常放行 ResourceResponse::Continue } })
拦截自定义协议请求
.protocol_handler("myapp", |request| { println!("自定义协议请求路径: {}", request.url()); // 返回自定义文本响应 Ok(ResourceResponse::new( 200, vec![("Content-Type".to_string(), "text/plain".to_string())], b"Handled custom protocol request".to_vec(), )) })
注意事项
on_resource_request会拦截所有资源请求,建议通过URL前缀、请求方法等条件过滤你需要关注的请求,避免影响页面正常加载。- 部分Wry版本中,修改原请求(如添加Headers)需要通过
ResourceResponse::Request返回新的请求对象,具体可参考对应版本的官方文档。 - 请求Body仅在POST、PUT等包含Body的请求中存在,且为字节数组形式,需根据实际内容类型解析(如JSON、表单数据)。
内容的提问来源于stack exchange,提问作者prabhupant
相关产品推荐
相关产品推荐

