使用AFNetworking进行基本身份验证

时间:2015-07-25 03:30:42

标签: ios objective-c iphone http afnetworking

我是iOS开发的新手,如何在Objective-C中使用AFNetworking进行HTTP基本身份验证?

如何使用它?

- (Void) setAuthorizationHeaderWithUsername: (NSString *) username password: (NSString *) password

3 个答案:

答案 0 :(得分:1)

当您需要添加标头或扩展标头时,您应该创建自己的AFHTTPClient实例。您可以将sharedInstance创建为singleton,然后调用instance方法来设置用户名和密码。

+ (AFHTTPClient *)sharedClient{
    static AFHTTPClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
            _sharedClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"your_server_url"]];
        [_sharedClient setAuthorizationHeaderWithUsername:@"username" password:@"password"];
    });

    return _sharedClient;
}

答案 1 :(得分:0)

感谢您的帮助,但失败了。

您将返回以下错误:

Request failed: unacceptable content-type: text/html
NSLocalizedDescription = Request failed: unacceptable content-type: text/html.

我相信服务器正在text/html返回,代码期待JSON。

答案 2 :(得分:-3)

您可以使用AFN执行大部分网络请求。希望这可以帮到你。

- (Void) setAuthorizationHeaderWithUsername: (NSString *) username password: (NSString *) password {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //a NSDictionary parameter
    NSDictionary *parameters = @{@"name": username, @"pwd": password};
    [manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //you can get JSON response in responseObject whether your request or wrong.
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
}