Managing HTTP Cookies on iPhone

前端 未结 3 1026
一整个雨季
一整个雨季 2020-11-28 20:00

I want to port a python app that uses mechanize for the iPhone. This app needs to login to a webpage and using the site cookie to go to other pages on that site to get some

相关标签:
3条回答
  • 2020-11-28 20:04

    You can use the NSURLConnection class to perform a HTTP request to login the website, and retrieve the cookie. To perform a request, just create an instance of NSURLConnection and assign a delegate object to it.

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    

    Then, implement a delegate method.

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        NSDictionary *fields = [httpResponse allHeaderFields];
        NSString *cookie = [fields valueForKey:@"Set-Cookie"]; // It is your cookie
    }
    

    Retain or copy the cookie string. When you want to perform another request, add it to your HTTP header of your NSURLRequest instance.

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
    [request addValue:cookie forHTTPHeaderField:@"Cookie"];
    
    0 讨论(0)
  • 2020-11-28 20:08

    @zonble's answer only works in my localhost; If the server is not running locally, the "Set-Cookie" header is missing from the NSDictionary *fields = [HTTPResponse allHeaderFields];

    Finally I found @benzado's solution works fine. Also see: iphone nsurlconnection read cookies @Tal Bereznitskey's answer.

    0 讨论(0)
  • 2020-11-28 20:15

    NSURLConnection gives you cookie management for free. From the URL Loading System Programming Guide:

    The URL loading system automatically sends any stored cookies appropriate for an NSURLRequest. unless the request specifies not to send cookies. Likewise, cookies returned in an NSURLResponse are accepted in accordance with the current cookie acceptance policy.

    0 讨论(0)
提交回复
热议问题