提问者:小点点

AFNetwork with AFHTTPClient with AFJSONask est操作//MIME类型问题


我一直在尝试在特定实例中掌握AFHTTPClient,该实例将请求发送到需要OAuth身份验证的基于REST的服务。使用GTMOAuth创建OAuth身份验证没有问题。

我还可以使用手工拼凑的NSMutableURLRequest以及AFJSONRequestOperation和NSURLConnection成功地整理参数以分派请求并获得格式良好的JSON响应。后两个机械师是我的精神检查,以确保我正确接触服务。

我使用

[AFHTTPClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)] 

但无论如何-

不,布埃诺。

这段代码不想返回任何类型的字典响应。

- (IBAction) testFlickr {
// marshall parameters
NSString *urlStr = @"http://api.flickr.com/";
NSURL *url = [NSURL URLWithString:urlStr];

AFHTTPClient *client = [[AFHTTPClient alloc]initWithBaseURL:url];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setParameterEncoding:AFJSONParameterEncoding];
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:@"json", @"format", @"66854529@N00", @"user_id", @"1", @"jsoncallback", nil];

NSString *path = [[NSString alloc]initWithFormat:@"services/rest/?method=flickr.people.getPhotos"];

NSMutableURLRequest *af_request = [client requestWithMethod:@"GET" path:path parameters:params];

// flickrAuth instance variable is an instance of GTMOAuthAuthentication
[self.flickrAuth authorizeRequest:af_request];

[client setAuthorizationHeaderWithToken:[self.flickrAuth accessToken]];
[client setDefaultHeader:@"Accept" value:@"application/json"];

[client requestWithMethod:@"GET" path:path parameters:params];

LOG_FLICKR_VERBOSE(0, @"Can Authorize? %@", ([self.flickrAuth canAuthorize] ? @"YES":@"NO"));
LOG_FLICKR_VERBOSE(0, @"%@", client);


// first way of trying..
AFHTTPRequestOperation *af_operation = [client HTTPRequestOperationWithRequest:af_request success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *str = [[NSString alloc] initWithData:responseObject
                                          encoding:NSUTF8StringEncoding];
    LOG_FLICKR_VERBOSE(0, @"Weird af_operation semantics, but.. %@", str);
    LOG_FLICKR_VERBOSE(0, @"Weird af_operation semantics returns %@", [responseObject class]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //
    LOG_FLICKR_VERBOSE(0, @"Weird af_operation semantics, error.. %@", error);

}];

[af_operation start];
}

这个请求通过了。响应数据本身是我所期望的,但它不是任何类型的字典类。

我宁愿继续使用AFHTTPClient的方法(例如,与[AFJSONRequestOperation-jsonrequestoperation-withrequest]相反),这样我就可以使用AFHTTPClient的可达性方法等等。

奇怪的是(至少对我来说)如果我这样做的话:

NSMutableURLRequest *aj_request = [client requestWithMethod:@"GET" path:path parameters:params];
[self.flickrAuth authorizeRequest:aj_request];

AFJSONRequestOperation *aj_operation = 
[AFJSONRequestOperation JSONRequestOperationWithRequest:af_request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    LOG_FLICKR_VERBOSE(0, @"AFJSONRequestOperation %@", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    LOG_FLICKR_VERBOSE(0, @"AFJSONREquestOperation Error %@", error);
}];

[aj_operation start];

它以“401”失败,因为它在响应头中期望application/json,而认为它是接收到的text/plain

但是,如果我这样做的话:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[[NSURL alloc]initWithString:@"http://api.flickr.com/services/rest/?method=flickr.people.getPhotos&format=json&user_id=66854529@N00&nojsoncallback=1"]];
[self.flickrAuth authorizeRequest:request];

AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                                                    LOG_FLICKR_VERBOSE(0, @"Success Flickr  =========\n%@ %@", JSON, [JSON valueForKeyPath:@"photos.total"]);
                                                    /////handler(JSON, nil);
                                                } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                    LOG_FLICKR(0, @"URL Was %@", url);
                                                    LOG_FLICKR(0, @"Failed Flickr  ==========\n%@ %@", error, JSON);
                                                    /////handler(nil, error);
                                                }];
[operation start];

它工作得很好,包括漂亮的JSON、字典格式的数据。

首先,我使用AFHTTPClient生成NSMutableURLRequest。在第二种情况下,我自己创建NSMutableURLRequest。在这两种情况下,我都使用AFJSONask est操作来发送请求,将问题的唯一罪魁祸首留给(除了我自己...)AFHTTPClient.

在我可以开始工作的第一个示例中,它没有返回JSON-y数据。

在第二个示例中,AFHTTPClient似乎创建了一个明显失败的NSMutableURLRequest-

我想知道-

帮助


共2个答案

匿名用户

在您的第一个代码示例中,它看起来像您正在执行NSMutableURLRequest*af_request=[客户端请求与方法:@"GET"path: path参数: params];,然后设置默认头。默认标头仅应用于指定后创建的请求。也许这就是事情出错的地方。

此外,401错误可能会抱怨其内容类型,但401是一个错误状态代码,表示您未经验证。

匿名用户

我最终删除了所有的头参数来隔离问题,但没有什么区别。仔细检查反应给了我一个线索。虽然Flickr确实返回了“JSON”,但它不是无林特的,似乎并且需要对其中一个参数进行调整。我一直在发送jsonCallback=1,但它应该是nojsonCallback=1。一旦我修复了该参数AFJSONask est操作将正确处理响应并解析JSON。

我的最终代码如下所示(对于其他代码,注意nojsoncallback=1参数)

- (IBAction)testFlickrAFJSON:(id)sender
{
// marshall parameters
NSString *urlStr = @"http://api.flickr.com/";
NSURL *url = [NSURL URLWithString:urlStr];
//NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:@"json", @"format", @"66854529@N00", @"user_id", nil];
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:@"json", @"format", @"66854529@N00", @"user_id", @"1", @"nojsoncallback", nil];
NSString *path = [[NSString alloc]initWithFormat:@"services/rest/?method=flickr.people.getPhotos"];

AFHTTPClient *client = [[AFHTTPClient alloc]initWithBaseURL:url];

NSMutableURLRequest *af_request = [client requestWithMethod:@"GET" path:path parameters:params];

[self.flickrAuth authorizeRequest:af_request];

LOG_FLICKR_VERBOSE(0, @"Can Authorize? %@", ([self.flickrAuth canAuthorize] ? @"YES":@"NO"));
AFJSONRequestOperation *af_operation_2 = [AFJSONRequestOperation JSONRequestOperationWithRequest:af_request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        LOG_FLICKR_VERBOSE(0, @"AFJSONRequestOperation Alt %@", JSON);
        LOG_FLICKR_VERBOSE(0,@"AFJSONRequestOperation Alt response MIMEType %@",[response MIMEType]);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        LOG_FLICKR_VERBOSE(0, @"AFJSONREquestOperation Alt Error %@", error);
        NSHTTPURLResponse *resp = [[error userInfo] valueForKey:AFNetworkingOperationFailingURLResponseErrorKey];
        LOG_FLICKR_VERBOSE(0,@"AFJSONRequestOperation Alt Error response MIMEType %@",[resp MIMEType]);

    }];

    [af_operation_2 start];

}