NSURL *url = [NSURL URLWithString:
@"https://www.baidu.com"];
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", response);
}] resume] ;
运行代码,通过控制台的输出,可以看到能够正常的获取到回执数据。
新建一个命名为NetworkProtocl的类,使其继承自NSURLProtocol,实现如下:
#import "NetworkProtcol.h"
@implementation NetworkProtcol
// 网络请求的代理需要注册,在load方法中进行注册
+ (void)load {
[NSURLProtocol registerClass:self];
}
// 1. 这个方法是第一步,需要判断是否要拦截当前的请
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
NSLog(@"canInitWithRequest: %@", request.URL.absoluteString);
// 根据标记判断,如果处理过了就不再拦截了
if ([self propertyForKey:@"Handle" inRequest:request]) {
return false;
}
return YES;
}
// 2. 处理请求,这里可以返回一个新的Request对象,可以对原Request进行修改
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
NSLog(@"canonicalRequestForRequest: %@", request.URL.absoluteString);
return request;
}
// 3. 这个方法处理拦截后的行为,可以做数据修改,本地mock或请求其他接口
- (void)startLoading {
NSLog(@"startLoading");
[NSURLProtocol setProperty:@YES forKey:@"Handle" inRequest:self.request];
[[[NSURLSession sharedSession] dataTaskWithRequest:self.request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
[self.client URLProtocolDidFinishLoading:self];
}] resume];
}
// 整个代理行为结束回调
- (void)stopLoading {
NSLog(@"stopLoading");
}
@end
再次运行,通过控制台的打印,可以看到网络代理已经可以正常的工作,如上面的示例代码所示,整个代理过程最重要的即是三步:
1. 判断某个请求是否要进行代理拦截。
2. 处理请求,可以进行修改。
3. 执行真正的拦截行为,并通过回调来返回结果给原请求方。
@interface NSURLProtocol : NSObject
// 初始化方法
- (instancetype)initWithRequest:(NSURLRequest *)request cachedResponse:(nullable NSCachedURLResponse *)cachedResponse client:(nullable id <NSURLProtocolClient>)client;
- (instancetype)initWithTask:(NSURLSessionTask *)task cachedResponse:(nullable NSCachedURLResponse *)cachedResponse client:(nullable id <NSURLProtocolClient>)client;
// SessionTask对象
@property (nullable, readonly, copy) NSURLSessionTask *task
// 客户端对象,用来回调原请求方
@property (nullable, readonly, retain) id <NSURLProtocolClient> client;
// 当前处理的请求对象
@property (readonly, copy) NSURLRequest *request;
// Response缓存
@property (nullable, readonly, copy) NSCachedURLResponse *cachedResponse;
// 这个方法必须子类实现,用来判断是否要拦截某个请求
+ (BOOL)canInitWithRequest:(NSURLRequest *)request;
+ (BOOL)canInitWithTask:(NSURLSessionTask *)task;
// 这个方法必须子类实现,用来对请求进行修改
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;
// 这个方法用来判断是否要使用缓存请求,判断要进行的请求与缓存的是否相同
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b;
// 开始拦截行为
- (void)startLoading;
// 整个拦截行为结束
- (void)stopLoading;
// 用来给某个请求打标签,可以防止请求拦截出现递归
+ (void)setProperty:(id)value forKey:(NSString *)key inRequest:(NSMutableURLRequest *)request;
// 获取标签
+ (nullable id)propertyForKey:(NSString *)key inRequest:(NSURLRequest *)request;
// 删除标签
+ (void)removePropertyForKey:(NSString *)key inRequest:(NSMutableURLRequest *)request;
// 注册网络代理类
+ (BOOL)registerClass:(Class)protocolClass;
// 注销注册的代理
+ (void)unregisterClass:(Class)protocolClass;
@end
其中,client属性用来与原请求方交互,其协议的方法如下:
@protocol NSURLProtocolClient <NSObject>
// 触发客户端的重定向回调
- (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse;
// 触发客户端的缓存有效性回调
- (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse;
// 触发客户端的接收回执回调
- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy;
// 触发客户端的接收数据回调
- (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data;
// 触发客户端的请求完成回调
- (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol;
// 触发客户端的请求失败回调
- (void)URLProtocol:(NSURLProtocol *)protocol didFailWithError:(NSError *)error;
// 触发客户端的用户认证回调
- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
// 触发客户端的取消用户认证回调
- (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
@end
#import "NetworkProtcol.h"
@interface NetworkProtcol ()<NSURLSessionDelegate>
@property (atomic,strong,readwrite) NSURLSessionDataTask *task;
@property (nonatomic,strong) NSURLSession *session;
@end
@implementation NetworkProtcol
+ (void)load {
[NSURLProtocol registerClass:self];
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
//只处理http和https请求
NSString *scheme = [[request URL] scheme];
if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||
[scheme caseInsensitiveCompare:@"https"] == NSOrderedSame)) {
//看看是否已经处理过了,防止无限循环
if ([NSURLProtocol propertyForKey:@"Handle" inRequest:request]) {
return NO;
}
return YES;
}
return NO;
}
+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
- (void)startLoading
{
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
//打标签,防止无限循环
[NSURLProtocol setProperty:@YES forKey:@"Handle" inRequest:mutableReqeust];
NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
self.session = [NSURLSession sessionWithConfiguration:configure delegate:self delegateQueue:queue];
self.task = [self.session dataTaskWithRequest:mutableReqeust];
[self.task resume];
}
- (void)stopLoading
{
[self.session invalidateAndCancel];
self.session = nil;
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
if (error != nil) {
[self.client URLProtocol:self didFailWithError:error];
}else
{
[self.client URLProtocolDidFinishLoading:self];
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
[self.client URLProtocol:self didLoadData:data];
}
@end
如果使用的是WKWebView,则无法直接被拦截,需要做如下的额外处理:
Class cls = [[[WKWebView new] valueForKey:@"browsingContextController"] class];
SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if ([cls respondsToSelector:sel]) {
// 通过 http 和 https 的请求,同理可通过其他的 Scheme 但是要满足 URL Loading System
[cls performSelector:sel withObject:@"http"];
[cls performSelector:sel withObject:@"https"];
}
WKWebView *web = [[WKWebView alloc] initWithFrame:self.view.frame];
[self.view addSubview:web];
NSURL *url = [NSURL URLWithString:
@"https://www.baidu.com"];
[web loadRequest:[NSURLRequest requestWithURL:url]];
需要注意,这里会涉及到一些私有属性和方法,可能会存在提审风险。
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h