Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A standalone iOS & OSX class for intercepting and proxying HTTP requests (e.g. from a Web View)

License

NotificationsYou must be signed in to change notification settings

marcuswestin/WebViewProxy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

99 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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.

API

1: Register handlers withWebViewProxy to intercept requests

+ (void) handleRequestsWithScheme:(NSString*)scheme handler:(WVPHandler)handler;

Intercept all UIWebView requests with the given scheme.

Examples:

[WebViewProxyhandleRequestsWithScheme:@"my_custom_scheme"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
+ (void) handleRequestsWithHost:(NSString*)host handler:(WVPHandler)handler;

Intercept all UIWebView requests with the given host.

Examples

[WebViewProxyhandleRequestsWithHost:@"foo"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
+ (void) handleRequestsWithHost:(NSString*)host path:(NSString*)path handler:(WVPHandler)handler;

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!"];}];
+ (void) handleRequestsMatching:(NSPredicate*)predicate handler:(WVPHandler)handler;

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!"];}];

2: Respond through theWVPResponse

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 fromNSURLConnection through theWVPResponse

High level response API

Descriptions and examples will be fleshed out.

- (void) respondWithImage:(UIImage*)image;

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];}];
- (void) respondWithImage:(UIImage*)image mimeType:(NSString*)mimeType;

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"];}];
- (void) respondWithText:(NSString*)text;

Respond with a text response (sent with Content-Type "text/plain"):

[WebViewProxyhandleRequestsWithHost:@"textExample"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"Hi!"];}];
- (void) respondWithHTML:(NSString*)html;

Respond with HTML (sent with Content-Type "text/html"):

[WebViewProxyhandleRequestsWithHost:@"htmlExample"handler:^(NSURLRequest* req, WVPResponse *res) {[resrespondWithText:@"<div class='notification'>Hi!</div>"];}];
- (void) respondWithJSON:(NSDictionary*)jsonObject;

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" }'}];

Low level response API

Descriptions and examples will be fleshed out.

- (void) respondWithStatusCode:(NSInteger)statusCode text:(NSString*)text;

Respond with the given HTTP status code and text.

Examples

[resrespondWithStatusCode:400text:@"Bad request"];[resrespondWithStatusCode:404text:@"Not found"];
- (void) setHeader:(NSString*)headerName value:(NSString*)headerValue;

Set a response header before responding.

Examples

[ressetHeader:@"Content-Type"value:@"image/gif"];[ressetHeader:@"Content-Type"value:@"audio/wav"];[ressetHeader:@"Host"value:@"WebViewProxy"];
- (void) setHeaders:(NSDictionary*)headers;

Set multiple response headers before responding.

Examples

[ressetHeaders:@{@"Content-Type":@"image/gif",@"Host":@"WebViewProxy" }];
- (void) respondWithData:(NSData*)data mimeType:(NSString*)mimeType;

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"
NSURLCacheStoragePolicy cachePolicy (property)

The cache policy for the response. Default value isNSURLCacheStorageNotAllowed

Examples

response.cachePolicy = NSURLCacheStorageAllowed;response.cachePolicy = NSURLCacheStorageAllowedInMemoryOnly;response.cachePolicy = NSURLCacheStorageNotAllowed;

Proxy requests to remote servers

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

Piping response API

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.

- (void) pipeResponse:(NSURLResponse*)response;

Pipe an NSURLResponse into the response.

- (void) pipeData:(NSData*)data;

Pipe data into the response.

- (void) pipeError:(NSError*)error;

Pipe an error into the response (e.g a network error).

- (void) pipeEnd;

Finish a piped response.

3: (optional) Handle "Stop Loading" event

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

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp