gpt4 book ai didi

ios - 使用 AFNetworking 进行基本身份验证

转载 作者:行者123 更新时间:2023-12-01 17:30:13 25 4
gpt4 key购买 nike

我正在尝试调用 URL 并返回 json 对象。但是,我无法找到在 AFNetworking 操作中放置基本身份验证的位置。我可以使用 POSTMAN 获取我的 JSON 对象,如下所示。

AFNetworking 操作的代码片段:

    NSString *string = @"MYURL";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
int total_count = (int)[[responseObject valueForKey:@"total_count"] integerValue];
if (total_count > 0) {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:total_count];
for (int i = 1; i <= total_count; i++) {
NSString *key = [NSString stringWithFormat:@"%i", i];
id object = [responseObject objectForKey:key];
[array addObject:object];
}
menuArray=array;
tableData = [NSArray arrayWithArray:array];
[categoryTableView reloadData];
}
else
{
NSLog(@"There is no internet connection!");
}

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"There is no internet connection!"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];

这是 POSTMAN,使用基本授权调用 URL

POSTMAN, callingURL with Basic Authorization

最佳答案

您需要将身份验证放在 header 中。你可以这样做:

//creating crequest    
NSURL *url = [NSURL URLWithString:YOUR_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//Encode username and password

NSData *plainData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *encodedUsernameAndPassword = [plainData base64EncodedStringWithOptions:0];

//set auth header
[request addValue:[NSString stringWithFormat:@"Basic %@", encodedUsernameAndPassword] forHTTPHeaderField:@"Authorization"];

// your AFNetworking code

关于ios - 使用 AFNetworking 进行基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27694112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com