0

OAuth 認証を必要とする REST ベースのサービスにリクエストをディスパッチする特定のインスタンスで AFHTTPClient を把握しようとしています。GTMOAuth を使用して OAuth 認証を作成することに問題はありません。

また、パラメーターを適切にマーシャリングしてリクエストをディスパッチし、手作業で調整した NSMutableURLRequest と、AFJSONRequestOperation と NSURLConnection の両方を使用して整形式の JSON レスポンスを取得することもできます。後者の 2 つのメカニズムは、私がサービスに正しく触れているかどうかの健全性チェックでした。

を使用して応答を取得します

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

しかし、それはテキスト/プレーンとして解釈されます。返されるオブジェクトのクラスは __NCFData です。

ブエノなし。

このコードは、何らかの辞書である応答を返したくありません。

- (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 の Reachability メソッドなどを使用できるように、([AFJSONRequestOperation JSONRequestOperationWithRequest] などではなく) 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 を生成しています。2 番目の例では、自分で NSMutableURLRequest を作成しています。どちらの場合も、AFJSONRequestOperation を使用してリクエストをディスパッチし、問題の唯一の原因を (私以外に..) AFHTTPClient に残しています。

作業を開始できる最初の例では、JSON-y データが返されていません。

2 番目の例では、AFHTTPClient は明らかに失敗する NSMutableURLRequest を作成しているように見えますが、(AFAICT) [NSMutableURLRequest requestWithURL] を使用して「手動で」その URL を作成すると、同じ URL が成功します。

AFHTTPClient を使用する際に何が欠けているのでしょうか?

ヘルプ?

4

2 に答える 2

2

NSMutableURLRequest *af_request = [client requestWithMethod:@"GET" path:path parameters:params];最初のコード例では、後でデフォルトのヘッダーを設定しているように見えます。デフォルトのヘッダーは、指定後に作成されたリクエストにのみ適用されます。多分それは物事がうまくいかないところです。

また、その 401 エラーはそのコンテンツ タイプについて不平を言っている可能性がありますが、401 はエラー ステータス コードであり、認証されていないことを意味します。

于 2012-11-02T15:31:20.103 に答える
0

問題を切り分けるためにすべてのヘッダー パラメータを削除することになりましたが、違いはありませんでした。応答をかなり詳しく調べると、手がかりが得られました。Flickr は「JSON」を返しますが、Lint-free ではなく、パラメーターの 1 つを微調整する必要があるようです。jsoncallback=1 を送信していましたが、nojsoncallback=1 のはずです。パラメータ AFJSONRequestOperation を修正すると、応答が正しく処理され、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];

}
于 2012-11-02T20:57:29.233 に答える