gpt4 book ai didi

ios - NSXMLparser 在 IOS swift 中具有基本身份验证

转载 作者:行者123 更新时间:2023-11-30 14:08:30 24 4
gpt4 key购买 nike

我们有一个 Web 服务,需要身份验证才能获取 XML 数据。现在我正在 swift 中编写代码来解析此 XML 请求。我正在使用 NSXML 解析器。但它不适用于身份验证。在哪里传递这些凭据?

最佳答案

使用 AFNetworking ,使用 AFHTTPRequestOperation 你可以传递凭据。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:@"http://188.40.74.207:8888/api/customer" parameters:nil error:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//[operation setCredential:credential];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"admin" password:@"admin"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {


NSLog(@"Success: %@", [operation responseString]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
[manager.operationQueue addOperation:operation];


[manager GET:@"http://188.40.74.207:8888/api/customer" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSLog(@"JSON: %@", responseObject);
arr_Response = responseObject;
// NSLog(@"Arr count is: %lu", (unsigned long)arr_Response.count);
[SVProgressHUD dismiss];

[self parseData];


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

或者不使用第三方,您可以使用下面的代码。

NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self username], [self password]];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
[theRequest setValue:authValue forHTTPHeaderField:@"Authorization"];

或者你可以尝试下面的代码。NSURLConnection有一个委托(delegate)方法

// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSLog(@"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
password:@"PASSWORD"
persistence:NSURLCredentialPersistenceForSession];
NSLog(@"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(@"responded to authentication challenge");
}
else {
NSLog(@"previous authentication failure");
}
}

关于ios - NSXMLparser 在 IOS swift 中具有基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32048647/

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