- Notifications
You must be signed in to change notification settings - Fork118
A standalone iOS & OSX class for intercepting and proxying HTTP requests (e.g. from a Web View)
License
marcuswestin/WebViewProxy
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Proxy requests for a web views, easily and without mucking around with NSURLProtocol.
Works on iOS and OSX.
Responses to intercepted requests may be served either synchronously or asynchronously - this stands in contrast to theUIWebViewDelegate method-(NSCachedURLResponse *)cachedResponseForRequest:url:host:path:, which may only intercept requests and serve responses synchronously (making it impossible to e.g. proxy requests through to the network without blocking on the network request).
If you like WebViewProxy you should also check outWebViewJavascriptBridge.
Intercept all UIWebView requests with the given scheme.
Examples:
[WebViewProxyhandleRequestsWithScheme:@"my_custom_scheme"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
Intercept all UIWebView requests with the given host.
Examples
[WebViewProxyhandleRequestsWithHost:@"foo"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
Intercept all UIWebView requests matching the given host and URL path.
Examples
[WebViewProxyhandleRequestsWithHost:@"foo.com"path:@"/bar"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
+ (void) handleRequestsWithHost:(NSString*)host pathPrefix:(NSString*)pathPrefix handler:(WVPHandler)handler;
Intercept all UIWebView requests matching the given host and URL path prefix.
For example, a handler registered with[WebViewProxy handleRequestsWithHost:@"foo.com" pathPrefix:@"/bar" handler:...] will intercept requests forhttp://foo.com/bar,https://foo.com/bar/cat?wee=yes,http://foo.com/bar/arbitrarily/long/subpath, etc.
Examples
[WebViewProxyhandleRequestsWithHost:@"foo.com"pathPrefix:@"/bar"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
Intercept all UIWebView requests where theNSURL matches the givenNSPredicate.
Examples
[WebViewProxyhandleRequestsMatching:[NSPredicatepredicateWithFormat:@"absoluteStringMATCHES[cd] '^http:'"]handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];[WebViewProxyhandleRequestsMatching:[NSPredicatepredicateWithFormat:@"hostMATCHES[cd] '[foo|bar]'"]handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
All registered handlers are given aWVPRespone* res. You respond to the request by calling methods on this object.
There are 3 type of APIs for responding to a request
- High level API for responding with an image, text, html or json
- Low level API for responding with specific HTTP headers and NSData
- Piping API for passing data/errors from
NSURLConnectionthrough theWVPResponse
Descriptions and examples will be fleshed out.
Respond with an image (sent with Content-Type "image/png" by default, or "image/jpg" for requests that end in.jpg or.jpeg):
Examples
[WebViewProxyhandleRequestsWithHost:@"imageExample"path:@"GoogleLogo.png"handler:^(NSURLRequest* req, WVPResponse *res) {UIImage* image = [UIImageimageNamed:@"GoogleLogo.png"];[resrespondWithImage:image];}];
Respond with an image and the given mime type.
Examples
[WebViewProxyhandleRequestsWithHost:@"imageExample"handler:^(NSURLRequest* req, WVPResponse *res) {UIImage* image = [UIImageimageNamed:@"GoogleLogo.png"];[resrespondWithImage:imagemimeType:@"image/png"];}];
Respond with a text response (sent with Content-Type "text/plain"):
[WebViewProxyhandleRequestsWithHost:@"textExample"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
Respond with HTML (sent with Content-Type "text/html"):
[WebViewProxyhandleRequestsWithHost:@"htmlExample"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"<div class='notification'>Hi!</div>"];}];
Respond with JSON (sent with Content-Type "application/json"):
[WebViewProxyhandleRequestsWithHost:@"textExample"handler:^(NSURLRequest* req, WVPResponse *res) {NSDictionary* jsonObject = [NSDictionarydictionaryWithObject:@"foo"forKey:@"bar"];[resrespondWithJSON:jsonObject];// sends '{ "bar":"foo" }'}];
Descriptions and examples will be fleshed out.
Respond with the given HTTP status code and text.
Examples
[resrespondWithStatusCode:400text:@"Bad request"];[resrespondWithStatusCode:404text:@"Not found"];
Set a response header before responding.
Examples
[ressetHeader:@"Content-Type"value:@"image/gif"];[ressetHeader:@"Content-Type"value:@"audio/wav"];[ressetHeader:@"Host"value:@"WebViewProxy"];
Set multiple response headers before responding.
Examples
[ressetHeaders:@{@"Content-Type":@"image/gif",@"Host":@"WebViewProxy" }];
Respond with the given data and mime type (the mime type gets sent as the HTTP headerContent-Type).
If mimeType is nil, WebWiewProxy attempts to infer it from the request URL path extension.
Examples
NSString* greeting =@"Hi!";NSData* data = [greetingdataUsingEncoding:NSUTF8StringEncoding];[resrespondWithData:datamimeType:@"text/plain"];
- (void) respondWithData:(NSData*)data mimeType:(NSString*)mimeType statusCode:(NSInteger)statusCode;
Respond with the given data, mime type and HTTP status code (the mime type gets sent as the HTTP headerContent-Type).
If mimeType is nil, WebWiewProxy attempts to infer it from the request URL path extension.
Examples
NSData* data = [@"<div>Item has been created</div>"dataUsingEncoding:NSUTF8StringEncoding];[resrespondWithData:datamimeType:@"text/html"statusCode:201];[resrespondWithData:nilmimeType:nilstatusCode:304];// HTTP status code 304 "Not modified"[resrespondWithData:nilmimeType:nilstatusCode:204];// HTTP status code 204 "No Content"
The cache policy for the response. Default value isNSURLCacheStorageNotAllowed
Examples
response.cachePolicy = NSURLCacheStorageAllowed;response.cachePolicy = NSURLCacheStorageAllowedInMemoryOnly;response.cachePolicy = NSURLCacheStorageNotAllowed;
There are many ways to proxy remote requests withWebViewProxy.
The easiest approach usesWebViewProxyResponse as aNSURLConnection delegate. This pipes the response through the proxy response:
[WebViewProxyhandleRequestsWithHost:@"example.proxy"handler:^(NSURLRequest *req, WVPResponse *res) {NSString* proxyUrl = [req.URL.absoluteStringstringByReplacingOccurrencesOfString:@"example.proxy"withString:@"example.com"];NSURLRequest* proxyReq = [NSURLRequestrequestWithURL:[NSURLURLWithString:proxyUrl]]; [NSURLConnectionconnectionWithRequest:proxyReqdelegate:res];}];
Another approach which gives you more control but reads the entire response into memory:
[WebViewProxyhandleRequestsWithHost:@"example.proxy"handler:^(NSURLRequest *req, WVPResponse *res) {NSString* proxyUrl = [req.URL.absoluteStringstringByReplacingOccurrencesOfString:@"example.proxy"withString:@"example.com"];NSURLRequest* proxyReq = [NSURLRequestrequestWithURL:[NSURLURLWithString:proxyUrl]];NSOperationQueue* queue = [NSOperationQueuenew]; [NSURLConnectionsendAsynchronousRequest:proxyReqqueue:queuecompletionHandler:^(NSURLResponse* proxyRes,NSData* proxyData,NSError* proxyErr) {if (proxyErr) {return [respipeError:proxyErr]; }else {NSInteger statusCode = [(NSHTTPURLResponse*)proxyResstatusCode]; [ressetHeaders:[(NSHTTPURLResponse*)proxyResallHeaderFields]]; [resrespondWithData:proxyDatamimeType:proxyRes.MIMETypestatusCode:statusCode]; } }];}];
Pipe anNSURLResponse and its data into theWVPResponse. This makes it simple to e.g. proxy a request and its response through an NSURLConnection.
Examples to be written.
Pipe an NSURLResponse into the response.
Pipe data into the response.
Pipe an error into the response (e.g a network error).
Finish a piped response.
A request handler may be told to "stop loading". This can happen e.g as a result ofcancel: being called on the underlyingNSURLRequest. You can get notified of this via thehandleStopLoadingRequest: method onWVPResponse.
This API can be used to e.g stop performing an expensive computation in your request handler.
Examples
[WebViewProxyhandleRequestsMatching:predicatehandler:^(NSURLRequest* req, WVPResponse *res) {NSOperation* expensiveOperation = [selfstartExpensiveOperation]; [reshandleStopLoadingRequest:^{ [expensiveOperationcancel] }];}];
About
A standalone iOS & OSX class for intercepting and proxying HTTP requests (e.g. from a Web View)
Resources
License
Uh oh!
There was an error while loading.Please reload this page.