Objective-c HTTP Basic authentication

后端 未结 3 1912
青春惊慌失措
青春惊慌失措 2021-02-06 09:29

How would i go about replicating this in objective-c

curl -u rick@email.com:mypassword http://foo.lighthouseapp.com/projects.xml

I\'ve been pla

3条回答
  •  情歌与酒
    2021-02-06 10:07

    If don't want use any frameworks (like me) you can do in the next way:

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

提交回复
热议问题