5

私は最近、iOS を学ぶために CodeSchool コースを受講しましたが、AFNetworkingを使用してサーバーと対話することを推奨しています。

サーバーから JSON を取得しようとしていますが、いくつかのパラメーターを URL に渡す必要があります。これらのパラメータにはユーザー パスワードが含まれているため、URL に追加したくありません。

単純な URL リクエストの場合、次のコードがあります。

NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/usersignin"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation
       JSONRequestOperationWithRequest:request
               success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                        NSLog(@"%@",JSON);
               } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                        NSLog(@"NSError: %@",error.localizedDescription);             
               }];

[operation start];

NSURLRequestのドキュメントを確認しましたが、そこから役立つものは何も得られませんでした。

サーバーで読み取られるように、このリクエストにユーザー名とパスワードを渡すにはどうすればよいですか?

4

2 に答える 2

6

次を使用できますAFHTTPClient

NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];

NSURLRequest *request = [client requestWithMethod:@"POST" path:@"usersignin" parameters:@{"key":@"value"}];

AFJSONRequestOperation *operation = [AFJSONRequestOperation
   JSONRequestOperationWithRequest:request
           success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                    NSLog(@"%@",JSON);
           } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                    NSLog(@"NSError: %@",error.localizedDescription);             
           }];

[operation start];

オペレーションを手動で作成して開始するのではなく、サブクラスAFHTTPClient化してそのメソッドを使用するのが理想的です。postPath:parameters:success:failure:

于 2013-05-17T14:55:03.180 に答える
2

この方法で NSURLRequest に POST パラメータを設定できます。

NSString *username = @"theusername";
NSString *password = @"thepassword";

[request setHTTPMethod:@"POST"];
NSString *usernameEncoded = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *passwordEncoded = [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString *postString = [NSString stringWithFormat:[@"username=%@&password=%@", usernameEncoded, passwordEncoded];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

つまり、URL でパラメーターを渡す場合と同じ方法でクエリ文字列を作成しますが、メソッドを に設定し、 URLPOSTの の後ろではなく、HTTP 本文に文字列を配置し?ます。

于 2013-05-17T14:45:30.627 に答える