How to set a Cookie with a NSURLRequest?

后端 未结 4 2041
一向
一向 2020-12-30 04:53

I\'m trying to create an login in my iPhone App.

NSURL *urlNew = [NSURL URLWithString:urlstring];
NSMutableURLRequest *theRequest = [NSMutableURLRequest req         


        
4条回答
  •  [愿得一人]
    2020-12-30 05:37

    There is source code to extract cookie string from NSHTTPURLResponse:

    static NSString *CookieFromResponse(NSHTTPURLResponse *response) {
        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:response.allHeaderFields forURL:response.URL];
    
        NSMutableString *cookieStr = [NSMutableString string];
        for (NSHTTPCookie *cookie in cookies) {
            if (cookieStr.length) {
                [cookieStr appendString:@"; "];
            }
            [cookieStr appendFormat:@"%@=%@", cookie.name, cookie.value];
        }
        return cookieStr.length ? cookieStr : nil;
    }
    

    And to set cookie string to NSMutableURLRequest:

    NSString *cookieStr = CookieFromResponse(response);
    [request addValue:cookieStr forHTTPHeaderField:@"Cookie"];
    

提交回复
热议问题