我们有一个需要身份验证来获取 XML 数据的 Web 服务。现在我正在快速编写代码来解析这个 XML 请求。我正在使用 NSXML 解析器。但它不适用于身份验证。在哪里传递这些凭据?
问问题
259 次
1 回答
0
使用 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 有一个委托方法
// 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");
}
}
于 2015-08-17T11:05:06.780 回答