8

簡単な裏話として、以前の開発者は ASIHTTPRequest を使用して POST リクエストを作成し、Web サービスからデータを取得しました。不明な理由により、アプリのこの部分が機能しなくなりました。将来の証明と AFNetworking を使用するのに十分な時間のように思えました。REST Web サービスは CakePHP フレームワークで実行されます。

つまり、AFNetworking を使用して要求応答文字列を受信して​​いません。

curl を使用してデータを正常に投稿し、適切な応答を受け取ることができるため、Web サービスが機能していることはわかっています。 /api/class/function.plist

以前の開発者の指示に従って、次のことを思いつきました。

#import "AFHTTPRequestOperation.h"    

…

- (IBAction)loginButtonPressed {

    NSURL *url = [NSURL URLWithString:@"https://example.com/api/class/function.plist"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setValue:[usernameTextField text] forHTTPHeaderField:@"data[User][email]"];

    [request setValue:[passwordTextField text] forHTTPHeaderField:@"data[User][password]"];

    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  

        NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);

        NSLog(@"response string: %@ ", operation.responseString);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"error: %@", operation.responseString);

    }];

    [operation start];

}

出力: 操作 hasAcceptableStatusCode: 200 応答文字列: 空の plist ファイル

試みられた解決策 1: AFNetworking Post Request 提案された解決策は、actionWithRequest と呼ばれる AFHTTPRequestOperation の関数を使用します。ただし、上記のソリューションを使用しようとすると、「クラス メソッド '+operationWithRequest:completion:' が見つかりません (戻り型のデフォルトは 'id' です]」という警告が表示されます。

試みられた解決策 2: NSURLConnection. 出力: 成功ログ メッセージは出力できますが、応答文字列は出力できません。*更新 - 空の plist を返します。

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *httpBodyData = @"data[User][email]=username@example.com&data[User][password]=awesomepassword";
[httpBodyData dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:[NSData dataWithContentsOfFile:httpBodyData]];
NSHTTPURLResponse __autoreleasing *response;
NSError __autoreleasing *error;
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];

// *update - returns blank plist
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData %@",str);

if (error == nil && response.statusCode == 200) {
    // Process response
    NSLog(@"success");//returns success code of 200 but blank
    NSLog(@"resp %@", response );
} else {
    // Process error
    NSLog(@"error");
}
4

2 に答える 2

18

これらは、Web サービスへの要求を満たすことになった基本的な (自分で使用するために作成した条件を取り除いた) 行です。@8vius と @mattt の提案に感謝します!

- (IBAction)loginButtonPressed {        
    NSURL *baseURL = [NSURL URLWithString:@"https://www.example.com/api/class"];

    //build normal NSMutableURLRequest objects
    //make sure to setHTTPMethod to "POST". 
    //from https://github.com/AFNetworking/AFNetworking
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
    [httpClient defaultValueForHeader:@"Accept"];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            [usernameTextField text], kUsernameField, 
                            [passwordTextField text], kPasswordField, 
                            nil];

    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" 
          path:@"https://www.example.com/api/class/function" parameters:params];

    //Add your request object to an AFHTTPRequestOperation
    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] 
                                      initWithRequest:request] autorelease];

    //"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
    //see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
    //mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
    //-still didn't prevent me from receiving plist data
    //[httpClient registerHTTPOperationClass:
    //         [AFPropertyListParameterEncoding class]];

    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    [operation setCompletionBlockWithSuccess:
      ^(AFHTTPRequestOperation *operation, 
      id responseObject) {
        NSString *response = [operation responseString];
        NSLog(@"response: [%@]",response);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@", [operation error]);
    }];

    //call start on your request operation
    [operation start];
    [httpClient release];
}
于 2012-04-03T21:07:57.053 に答える