UIWebView捕获响应头

时间:2013-03-18 12:11:07

标签: iphone ios uiwebview http-headers response

我搜索/搜索了很多但无法得到如何在UIWebview中捕获HTTP响应标头的答案。假设我在App Launch上的UIWebview中重定向到用户注册网关(已经处于活动状态),当用户完成注册时,应该通过在HTTP响应标头中传回的注册时分配给用户的成功唯一ID来通知应用程序。

是否有使用UIWebview捕获/打印HTTP响应标头的直接方法?

4 个答案:

答案 0 :(得分:19)

无法从UIWebView获取响应对象(提交苹果的错误,id说)

但有两个解决方法

1)通过共享NSURLCache

- (void)viewDidAppear:(BOOL)animated {
    NSURL *u = [NSURL URLWithString:@"http://www.google.de"];
    NSURLRequest *r = [NSURLRequest requestWithURL:u];
    [self.webView loadRequest:r];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSCachedURLResponse *resp = [[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request];
    NSLog(@"%@",[(NSHTTPURLResponse*)resp.response allHeaderFields]);
}
@end

如果这对您有用,这是理想的


ELSE

  1. 您可以完全使用NSURLConnection,然后只使用您下载的NSData来提供UIWebView :)
  2. 这是一个糟糕的解决方法! (正如理查德在评论中所指出的那样。)它有很大的缺点,你必须看看它是否是你案件中的有效解决方案

    NSURL *u = [NSURL URLWithString:@"http://www.google.de"];
    NSURLRequest *r = [NSURLRequest requestWithURL:u];
    [NSURLConnection sendAsynchronousRequest:r queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *resp, NSData *d, NSError *e) {
        [self.webView loadData:d MIMEType:nil textEncodingName:nil baseURL:u];
        NSLog(@"%@", [(NSHTTPURLResponse*)resp allHeaderFields]);
    }];
    

答案 1 :(得分:8)

我喜欢objective-c运行时。你有什么想做但却没有API吗? DM; HR

好的,更严肃的说,这是解决方案。它将捕获从CFNetwork发起的每个 URL响应,这是UIWebView碰巧在幕后使用的。它还将捕获AJAX请求,图像加载等。

为此添加过滤器可能就像对标题内容执行正则表达式一样简单。

@implementation NSURLResponse(webViewHack)

static IMP originalImp;

static char *rot13decode(const char *input)
{
    static char output[100];

    char *result = output;

    // rot13 decode the string
    while (*input) {
        if (isalpha(*input))
        {
            int inputCase = isupper(*input) ? 'A' : 'a';

            *result = (((*input - inputCase) + 13) % 26) + inputCase;
        }
        else {
            *result = *input;
        }

        input++;
        result++;
    }

    *result = '\0';
    return output;
}

+(void) load {
    SEL oldSel = sel_getUid(rot13decode("_vavgJvguPSHEYErfcbafr:"));

    Method old = class_getInstanceMethod(self, oldSel);
    Method new = class_getInstanceMethod(self, @selector(__initWithCFURLResponse:));

    originalImp = method_getImplementation(old);
    method_exchangeImplementations(old, new);
}

-(id) __initWithCFURLResponse:(void *) cf {
    if ((self = originalImp(self, _cmd, cf))) {
        printf("-[%s %s]: %s", class_getName([self class]), sel_getName(_cmd), [[[self URL] description] UTF8String]);

        if ([self isKindOfClass:[NSHTTPURLResponse class]])
        {
            printf(" - %s", [[[(NSHTTPURLResponse *) self allHeaderFields] description] UTF8String]);
        }

        printf("\n");
    }

    return self;
}

@end

答案 2 :(得分:1)

如果你想要更高级别的@Richard J. Ross III编写的API代码,你需要继承NSURLProtocol

NSURLProtocol是处理URL请求的对象。因此,您可以将其用于在NSHipsterRay Wenderlich上更好地描述的特定任务,其中包括从响应中获取HTTP标头的情况。

代码

从NSURLProtocol创建一个新的子类,你的.h文件应如下所示:

@interface CustomURLProtocol : NSURLProtocol <NSURLConnectionDelegate>

@property (nonatomic, strong) NSURLConnection *connection;

@end

你的.m文件应该有这些方法来处理你想要的

@implementation CustomURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    // Here you can add custom filters to init or not specific requests
    return YES;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    // Here you can modify your request
    return request;
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
    return [super requestIsCacheEquivalent:a toRequest:b];
}

- (void)startLoading {
    // Start request
    self.connection = [NSURLConnection connectionWithRequest:self.request delegate:self];
}

- (void) stopLoading {
    [self.connection cancel];
    self.connection = nil;
}

#pragma mark - Delegation

#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        // Here we go with the headers
        NSDictionary *allHeaderFields = [httpResponse allHeaderFields];
    }

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.client URLProtocol:self didLoadData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self.client URLProtocol:self didFailWithError:error];
}

最后要做的是将此协议注册到加载系统,这在AppDelegate上很容易实现:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSURLProtocol registerClass:[CustomURLProtocol class]];
    return YES;
}

答案 3 :(得分:-1)

NSHTTPURLResponse有类似

的方法
- (NSDictionary *)allHeaderFields

了解更多信息 https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/Reference/Reference.html#//apple_ref/occ/cl/NSHTTPURLResponse

编辑:抱歉,我没有想到UIWebView。如果您使用NSURLConnection

,我的解决方案就有效

但是,如果您使用NSURLConnection向webview提供,那么您就有机会捕获连接,包括响应标头。