28
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AFNetworkingのリクエストにCookieとUserAgentを設定する

Posted at
testGet
- (void)testGet
{
	NSString* url = @"http://hoge.com/get.hoge";
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    
    NSError* error = nil;
    NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET"
                                                                      URLString:url
                                                                     parameters:nil
                                                                          error:&error];
    
    if( error ){
        return;
    }
    
    NSArray* availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookiesForURL:
                                 [NSURL URLWithString:[NSString stringWithFormat:@"http://hoge.com]]];
    NSDictionary* headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];
    
    
    [request setAllHTTPHeaderFields:headers];
    [request setValue:@"UserAgent文字列" forHTTPHeaderField:@"User-Agent"];
    
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request
                                     success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"Cookie:%@",request.allHTTPHeaderFields[@"Cookie"]);
        NSLog(@"UserAgent:%@",request.allHTTPHeaderFields[@"User-Agent"]);
    }
	failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {   
        NSLog(@"NG");
    }];
    
	// 実行
    [manager.operationQueue addOperation:operation];
}

もっと簡単な書き方がある気がする。。

28
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?