开发者

Objective-c HTTP Basic authentication

开发者 https://www.devze.com 2023-01-24 02:52 出处:网络
How would i go about replicating this in objective-c curl -u rick@email.com:mypassword http://foo.lighthouseapp.com/projects.xml

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 playing around with the ASIHTTPRequest librar开发者_运维问答y but can't seem to figure it out,

obviously sending my request like so returns an authentication error:

-(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);
    }
}

This is probably very simple i'm just missing something pretty major


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


From ASIHTTPRequest Documentation

With a Request Header

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


If you are using ASIHTTPRequest, this is all that is needed:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号