0
我們有一個需要身份驗證來訪存XML數據的Web服務。現在我正在用swift編寫代碼來解析此XML請求。我正在使用NSXML分析器。 但它不適用於身份驗證。在哪裏傳遞這些憑據?在IOS中使用基本身份驗證的NSXMLparser
我們有一個需要身份驗證來訪存XML數據的Web服務。現在我正在用swift編寫代碼來解析此XML請求。我正在使用NSXML分析器。 但它不適用於身份驗證。在哪裏傳遞這些憑據?在IOS中使用基本身份驗證的NSXMLparser
使用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"];
或者你可以試試下面code.There是NSURLConnection的
// 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");
}
}
的一個委託方法是不可能的NSXMLParser,而無需使用任何外部庫? – PrasadK
嘗試更新一個。 – poojathorat
謝謝!!我設法迅速做到這一點,參考你的回答 – PrasadK