【问题标题】:Objective-c HTTP Basic authenticationObjective-c HTTP 基本认证
【发布时间】:2011-05-06 10:33:14
【问题描述】:

我将如何在objective-c中复制它

curl -u rick@email.com: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);
    }
}

这可能很简单,我只是错过了一些非常重要的东西

【问题讨论】:

    标签: objective-c authentication httpwebrequest lighthouse


    【解决方案1】:

    如果不想使用任何框架(如我),您可以通过以下方式进行:

    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];
    

    【讨论】:

    • 正是我需要的
    【解决方案2】:

    如果你使用的是 ASIHTTPRequest,这就是你所需要的:

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

    【讨论】:

      【解决方案3】:

      From ASIHTTPRequest Documentation

      With a Request Header

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

      【讨论】:

      • 谢谢它真的帮助了我
      猜你喜欢
      • 2016-07-27
      • 2012-01-06
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2011-05-03
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多