8

我将如何在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);
    }
}

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

4

3 回答 3

13

来自 ASIHTTPRequest 文档

带有请求标头

[request addRequestHeader:@"Authorization"
                    value:[NSString stringWithFormat:@"Basic %@",
                           [ASIHTTPRequest base64forData:
                            [[NSString stringWithFormat:@"%@:%@", theUsername, thePassword]
                             dataUsingEncoding:NSUTF8StringEncoding]]]];
于 2010-11-07T23:58:23.770 回答
12

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

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];
于 2016-03-05T06:59:25.293 回答
0

如果您使用的是 ASIHTTPRequest,则只需要以下内容:

 request.shouldPresentCredentialsBeforeChallenge = YES;
 [request addBasicAuthenticationHeaderWithUsername:@"USER" andPassword:@"PASSWORD"];
于 2014-03-25T14:14:17.283 回答