XML データを取得するために認証が必要な Web サービスがあります。現在、この XML 要求を解析するコードを迅速に作成しています。NSXML パーサーを使用しています。しかし、認証では機能しません。これらの資格情報をどこに渡すか?
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 のデリゲート メソッドが 1 つあります。
// 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 に答える