如何更新此已弃用的功能以使用AFNetworking 3.0?
AFHTTPRequestOperation *requestOperation=[[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_URLString]]];
[requestOperation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) {
if (redirectResponse) {
//this is the redirected url
NSLog(@"%@",request.URL);
}
return request;
}];
[requestOperation start];
答案 0 :(得分:12)
在setTaskWillPerformHTTPRedirectionBlock
上使用AFHTTPSessionManager
。如果初始URL请求重定向,则将调用块集。您可以选择遵循重定向,也可以停止阻止重定向。
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
NSLog(@"%@", request.URL);
// This will be called if the URL redirects
return request; // return request to follow the redirect, or return nil to stop the redirect
}];
[manager GET:_URLString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
我建议你仔细阅读AFNetworking 3.0 Migration Guide。
答案 1 :(得分:1)
在某些情况下,您需要为请求设置标头,只需使用requestSerializer
设置requestSerializer setValue: forHTTPHeaderField:
,如下所示:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
NSLog(@"%@", request.URL);
// This will be called if the URL redirects
return request; // return request to follow the redirect, or return nil to stop the redirect
}];
[manager GET:_URLString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];