我正在尝试使用AfNetworking AfHttpClient登录谷歌阅读器,但我得到了这个错误,我可以;似乎想通了。
以下是AFNetworking的子类:
// main url endpoints
#define GOOGLE_ACCOUNTS_BASE_URL @"https://www.google.com/accounts/"
@implementation ADPGoogleLoginClient
+ (ADPGoogleLoginClient *)sharedClient {
static ADPGoogleLoginClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[ADPGoogleLoginClient alloc] initWithBaseURL:[NSURL URLWithString:GOOGLE_ACCOUNTS_BASE_URL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFXMLRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Content-type" value:@"text/plain"];
[self setDefaultHeader:@"Accept" value:@"text/plain"];
return self;
}
@end
然后我尝试使用以下代码形成请求:
//set up request params
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"googlereader-ios-client", @"client",
[keychainCredentials objectForKey:(__bridge id)kSecAttrAccount], @"Email",
[keychainCredentials objectForKey:(__bridge id)kSecValueData], @"Passwd",
@"reader", @"service",
@"ipad", @"source", nil];
//make requests
[[ADPGoogleLoginClient sharedClient] getPath:@"ClientLogin"
parameters:params
success:^(AFHTTPRequestOperation *operation , id responseObject)
{
//parse out token and store in keychain
NSString* responseString = [operation responseString];
NSString* authToken = [[[responseString componentsSeparatedByString:@"\n"] objectAtIndex:2]
stringByReplacingOccurrencesOfString:@"Auth=" withString:@""];
keychainToken = [[KeychainItemWrapper alloc] initWithIdentifier:@"GReaderToken" accessGroup:nil];
[keychainToken setObject:authToken forKey:(__bridge id)kSecValueData];
loginSuccess();
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"There was an error logging into Reader - %@", [error localizedDescription]);
loginFailure(error);
}];
我将默认标题设置为
[self setDefaultHeader:@"Content-type" value:@"text/plain"];
[self setDefaultHeader:@"Accept" value:@"text/plain"];
所以我不确定为什么它仍然认为它期待xml?
答案 0 :(得分:6)
您正在为请求设置Content-Type
标头,但您看到的错误来自响应。为了使请求被视为“成功”,内容类型需要与期望相匹配(以避免在您期望XML时尝试解析JSON响应)。
在相同的错误代码中,它应该提到它实际返回的内容类型。如果它确实是XML,请使用AFXMLRequestOperation +addAcceptableContentTypes:
添加,并且一切都应该正常。
答案 1 :(得分:1)
嗨,马特,所以我刚开始测试这个。看起来我正在注册错误的AF操作。我改变了
[self registerHTTPOperationClass:[AFXMLRequestOperation class]];
到
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
一切都很好!