我正在修复现有项目中的错误。问题是AFHTTPClient期待一个有效的JSON响应,但服务器返回一些乱码,如“”操作完成\“”(所有的引号和括号都在返回)。这导致操作失败,并点击失败块,因为它无法解析响应。尽管如此,服务器返回状态码200,并且对操作完成感到高兴。
我有一个扩展AFHTTPClient的类(从我的.h文件开始)
@interface AuthClient : AFHTTPClient
//blah blah blah
@end
在我的实现文件中,类被初始化为:
- (id)initWithBaseURL:(NSURL *)url{
if (self = [super initWithBaseURL:url]) {
self.parameterEncoding = AFFormURLParameterEncoding;
self.stringEncoding = NSASCIIStringEncoding;
[self setDefaultHeader:@"Accept" value:@"application/json"];
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
}
return self;
}
我正在进行的通话是在上面提到的课程中完成的,并且如下所示:
- (void)destroyToken:(NSString *)token onCompletion:(void (^)(BOOL success))completion onFailure:(void (^)(NSError *error))failure{
[self postPath:@"TheServerURL" parameters:@{@"token": token} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
//Do some stuff
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//Don't want to be here.
}];
}
在失败块内部,错误在错误对象的_userInfo部分中返回为:
[0](null)@“NSDebugDescription”:@“JSON文本没有以数组或对象开头,并且选项允许未设置片段。”
错误代码是3480.
从谷歌搜索我收集我需要设置类似NSJSONReadingAllowFragments的东西,但我不知道给定当前设置的方式/位置。有没有人有任何想法?
答案 0 :(得分:1)
听起来响应根本不是JSON。那么,为什么不接受HTTP响应本身,而不是像JSON那样尝试处理它呢?
如果您要提交JSON格式请求,但只想恢复文本响应,则可以使用AFNetworking 2.0执行以下操作:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlString parameters:@{@"token":token} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
或者,在1.x:
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
client.parameterEncoding = AFJSONParameterEncoding;
NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:@{@"token" : token}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"response: %@", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[client enqueueHTTPRequestOperation:operation];