我将如何在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);
}
}
这可能非常简单,我只是遗漏了一些非常重要的东西
答案 0 :(得分:13)
From ASIHTTPRequest Documentation
[request addRequestHeader:@"Authorization"
value:[NSString stringWithFormat:@"Basic %@",
[ASIHTTPRequest base64forData:
[[NSString stringWithFormat:@"%@:%@", theUsername, thePassword]
dataUsingEncoding:NSUTF8StringEncoding]]]];
答案 1 :(得分:8)
如果不想使用任何框架(比如我),你可以采用下一种方式:
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 :(得分:0)
如果您正在使用ASIHTTPRequest,则只需以下所需:
request.shouldPresentCredentialsBeforeChallenge = YES;
[request addBasicAuthenticationHeaderWithUsername:@"USER" andPassword:@"PASSWORD"];