我在使用 AFJSONRequestOperation 时面临 1 个问题。我的 API 客户端如下
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
@interface MyAPIClient : AFHTTPClient
+ (MyAPIClient *)sharedAPIClient;
@end
// .m file
#import "MyAPIClient.h"
@implementation MyAPIClient
+ (MyAPIClient *)sharedAPIClient {
static MyAPIClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClient = [[MyAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBASE_URL]];
});
return sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:CONTENT_TYPE_FIELD value:CONTENT_TYPE_JSON_VALUE];
self.parameterEncoding = AFJSONParameterEncoding;
return self;
}
@end
现在,当我使用以下代码请求时,它会返回“null”响应
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:userName,@"email",password,@"password",nil];
NSMutableURLRequest *request = [[MyAPIClient sharedAPIClient] requestWithMethod:@"POST" path:@"login" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSDictionary *dictResponse = (NSDictionary*)JSON;
DLog(@"Login Success JSON: %@",JSON);
if (block) {
block(YES,nil);
}
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
DLog(@"Login Error:- %@",error);
if (block) {
block(NO,error);
}
}];
[operation start];
但是,当我使用 AFHTTPRequestOperation 时,它会使用已登录的使用信息返回正确的输出
NSURL *loginUrl = [NSURL URLWithString:kBASE_URL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:loginUrl];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
userName,@"email",password,@"password",nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"login" parameters:params];
//Notice the different method here!
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"Raw data Response: %@", responseObject);
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(@"Converted JSON : %@", jsonArray);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Error: %@", error);
}];
//Enqueue it instead of just starting it.
[httpClient enqueueHTTPRequestOperation:operation];
我的服务器返回 JSON 响应。上面的代码有什么问题?为什么 AFJSONRequestOperation 返回空响应而 AFHTTPRequestOperation 返回正确响应?任何形式的帮助表示赞赏。提前致谢