我正在向 UIWebView 发送请求。加载的网页上有 AJAX 调用。我需要分析 AJAX 流量以确定用户是否登录。为此,我在 AppDelegate 中安装了 NSURLCache:
MYURLCache *cache = [[MYURLCache alloc] init];
[NSURLCache setSharedURLCache:cache];
此 MYURLCache 类正确接收通过 webview 运行的流量。我只能终止 AJAX 调用。然后我生成一个自己的 AJAX 调用请求。这个从网络服务器返回完美的响应。所以现在要做的最后一步是构造 NSCachedURLResponse 返回对象。我也做到了这一点,但 webview 在返回对象时根本不执行任何操作。如果我只返回 nil,WebView 会正常加载所有内容(nil 是 NSURLCache 的消息,表示没有缓存任何内容,因此 WebView 应该开始自行加载它)。
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
if ([[[request URL] absoluteString] rangeOfString:@"/ajax/"].location == NSNotFound) {
return nil;
} else {
ASIHTTPRequest *asirequest = [ASIHTTPRequest requestWithURL:[request URL]];
[asirequest setValidatesSecureCertificate:NO];
[asirequest startSynchronous];
NSError *error = [asirequest error];
NSData* data = [[asirequest responseString] dataUsingEncoding:NSUTF8StringEncoding];
// Create the cacheable response
NSURLResponse *urlresponse = [[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"application/json" expectedContentLength:[data length] textEncodingName:@"UTF-8"];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:data];
NSLog(@"cachedResponse %@", cachedResponse);
NSLog(@"cachedResponse data %@", [[NSString alloc] initWithData:[cachedResponse data] encoding:NSUTF8StringEncoding]);
return cachedResponse;
}
return nil;
}
我找到了解决这个问题的方法...我认为这与丢失的标头有关。
如果我更换
NSURLResponse *urlresponse = [[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"application/json" expectedContentLength:[data length] textEncodingName:@"UTF-8"];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:data];
With
NSHTTPURLResponse *urlresponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:nil];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:data];
整个事情都有效。该答案还建议了请求的附加自定义标头。https://stackoverflow.com/a/15234850/274518
NSDictionary *headers = @{@"Access-Control-Allow-Origin" : @"*", @"Access-Control-Allow-Headers" : @"Content-Type"};
NSHTTPURLResponse *urlresponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:headers];
就我而言,我不需要它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)