2010-11-07 154 views
7

我將如何去在Objective-CObjective-C的HTTP基本身份驗證

curl -u [email protected]:mypassword http://foo.lighthouseapp.com/projects.xml 

我一直在玩與周圍的ASIHTTPRequest庫,但似乎無法弄清楚複製此,

明顯發送我的要求,像這樣將返回認證錯誤:

-(void)submit:(id)sender { 
    NSURL *url = [NSURL URLWithString:@"http://ldn.lighthouseapp.com/projects/63254-londonist-20/tickets.xml"]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    [request startSynchronous]; 
    NSError *error = [request error]; 
    if (!error) { 
     NSString *response = [request responseString]; 
     NSLog(@"response:%@",response); 
    } else { 
     NSLog(@"error:%@",error); 
    } 
} 

這可能是非常簡單的我只是失去了一些東西非常重大的

回答

12

From ASIHTTPRequest Documentation

With a Request Header

[request addRequestHeader:@"Authorization" 
        value:[NSString stringWithFormat:@"Basic %@", 
          [ASIHTTPRequest base64forData: 
          [[NSString stringWithFormat:@"%@:%@", theUsername, thePassword] 
          dataUsingEncoding:NSUTF8StringEncoding]]]]; 
+0

感謝它真的幫助了我 – mohitum 2013-02-15 06:26:37

0

如果您正在使用ASIHTTPRequest,這是所有需要:

request.shouldPresentCredentialsBeforeChallenge = YES; 
[request addBasicAuthenticationHeaderWithUsername:@"USER" andPassword:@"PASSWORD"]; 
2

如果不希望使用任何框架(比如我),你可以在下一步做:

NSURL *url = [NSURL URLWithString: @"https://api.github.com"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

[request setHTTPMethod:@"GET"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

NSString *authStr = [NSString stringWithFormat:@"%@:%@", login, password]; 
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]]; 
[request setValue:authValue forHTTPHeaderField:@"Authorization"]; 

NSURLSession *session = [NSURLSession sharedSession]; 
[[session dataTaskWithRequest:request 
     completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 
      if (!error) { 
       NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
       NSLog(@"%@",responseDictionary); 
      } 
     }] resume];