我正在尝试将旧的“ASIHTTP”代码更改为AFNetworking,并坚持这一点, 有人可以告诉我如何将这块代码转换为AFNetworking
NSString *urlString = [NSString stringWithFormat:kLogin];
NSURL *url= [NSURL URLWithString:urlString];
ASIFormDataRequest *request= [ASIFormDataRequest requestWithURL:url];
[activeRequests addObject:request];
[request setValidatesSecureCertificate:YES]; //SSL enforcement
[request addRequestHeader:@"Host" value:kHost];
[request addRequestHeader:@"Accept" value:@"application/xml, text/javascript, */*; q=0.01"];
[request addRequestHeader:@"Accept-Language" value:@"en-us,en;q=0.5"];
[request addRequestHeader:@"Accept-Encoding" value:@"gzip, deflate"];
[request addRequestHeader:@"Connection" value:@"keep-alive"];
[request addRequestHeader:@"X-Requested-With" value:@"XMLHttpRequest"];
[request addRequestHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", [Utils base64String:[NSString stringWithFormat:@"%@:%@", username, password]]]];
[request setDelegate:self];
[[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[ASIHTTPRequest clearSession];
[request setTimeOutSeconds:REQUEST_TIME_OUT_SECS];
[request startAsynchronous];
我已尝试过AFHTTPClient以及请求操作,但卡在身份验证部分。 并获得错误401。
我用于AFNetworking的代码,
NSString * urlString = [NSString stringWithFormat:kLogin]; NSURL * url = [NSURL URLWithString:urlString];
AppHTTPClient* httpClient = [[AppHTTPClient alloc] initWithBaseURL:url];
[httpClient setDefaultHeader:@"Host" value:kHost];
[httpClient setDefaultHeader:@"Accept" value:@"application/xml, text/javascript, */*; q=0.01"];
[httpClient setDefaultHeader:@"Accept-Language" value:@"en-us,en;q=0.5"];
[httpClient setDefaultHeader:@"Accept-Encoding" value:@"gzip, deflate"];
[httpClient setDefaultHeader:@"Connection" value:@"keep-alive"];
[httpClient setDefaultHeader:@"X-Requested-With" value:@"XMLHttpRequest"];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[httpClient setAuthorizationHeaderWithUsername:username password:password];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
path:nil
parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.allowsInvalidSSLCertificate = YES;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"2");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog([error localizedDescription]);
NSLog(operation.responseString);
}
];
[operation start];
答案 0 :(得分:0)
使用AFHTTPClient setAuthorizationHeaderWithUsername:password:方法处理身份验证。它应该起作用,至少在我的情况下确实如此。
答案 1 :(得分:0)
解决了!!
'ASIHTTP'默认添加'User-Agent',如 'App_Name_with_Version(iPad模拟器; iPhone OS 6.0; en_US)'和AFNetworking没有。 所以我在请求创建期间添加了这个并且现在正在工作。