Send custom headers with UIWebView loadRequest

前端 未结 4 1581
生来不讨喜
生来不讨喜 2020-12-24 03:02

I want to be able to send some extra headers with my UIWebView loadRequest method.

I have tried:

NSMutableURLRequest *req = [NSMutableUR         


        
4条回答
  •  生来不讨喜
    2020-12-24 04:01

    I find another way, Can use NSURLProtocol .

    -(BOOL)webView:(IMYVKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        NSMutableDictionary* mapObject = [NSMutableDictionary dictionary];
        mapObject[@"headers"] = request.allHTTPHeaderFields;
        mapObject[@"navigationType"] = @(navigationType);
        [webViewRequestMap setObject:mapObject forKey:request.URL.absoluteString];
        return YES;
    }
    

    webViewRequestMap is Static NSMutableDictionary*

    in Your Custom NSURLProtocol code:

        @interface IMYCustomURLProtocol : NSURLProtocol
    @end
    @implementation IMYCustomURLProtocol 
    +(void)load
    {
         [NSURLProtocol registerClass:self];
    }
    + (BOOL)canInitWithRequest:(NSURLRequest *)request
    {
        NSString* urlString = request.URL.absoluteString;
        NSDictionary* dictionary = webViewReuqestMap[urlString];
        if (dictionary)
        {
            [webViewRequestMap removeObjectForKey:urlString];
            if ([request isKindOfClass:[NSMutableURLRequest class]]) {
               [(id)request setValue:@"HAHA" forHTTPHeaderField:@"MeiYou Co.,Ltd"];
            }
        }
        return NO;
    }
    @end
    

提交回复
热议问题