0

我正在尝试将我的旧“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];
4

2 回答 2

0

使用 AFHTTPClient setAuthorizationHeaderWithUsername:password: 方法来处理认证。它应该可以工作,至少在我的情况下是可以的。

于 2013-07-30T08:24:02.387 回答
0

解决了 !!

默认情况下,“ASIHTTP”添加了“用户代理”,如“App_Name_with_Version (iPad Simulator; iPhone OS 6.0; en_US)”和 AFNetworking 不添加。所以我在请求创建期间添加了这个,现在它正在工作。

于 2013-07-31T06:21:05.147 回答