2013-05-17 39 views
5

Gần đây tôi đã theo dõi CodeSchool course to learn iOS và họ khuyên bạn nên sử dụng AFNetworking để tương tác với máy chủ.Thêm thông số để yêu cầu với AFNetworking

Tôi đang cố gắng lấy JSON từ máy chủ của mình, nhưng tôi cần chuyển một số thông số cho các url. Tôi không muốn thêm các tham số này vào URL vì chúng chứa mật khẩu người dùng.

Đối với yêu cầu URL đơn giản Tôi có đoạn mã sau:

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]; 

Tôi đã kiểm tra tài liệu của NSURLRequest nhưng đã không nhận được bất cứ điều gì hữu ích từ đó.

Làm cách nào để chuyển tên người dùng và mật khẩu cho yêu cầu này được đọc trong máy chủ?

Trả lời

6

Bạn có thể sử dụng một 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]; 

Tốt nhất, bạn muốn phân lớp AFHTTPClient và sử dụng phương pháp postPath:parameters:success:failure: của nó, thay vì tạo ra một hoạt động bằng tay và bắt đầu nó.

2

Bạn có thể thiết lập các thông số POST trên một NSURLRequest theo cách này:

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]]; 

Nói cách khác, bạn tạo một chuỗi truy vấn theo cùng một cách như khi bạn đang đi qua các tham số trong URL, nhưng thiết lập các phương pháp để POST và đặt chuỗi trong phần thân HTTP thay vì sau ? trong URL.

+0

Có, đằng sau khung cảnh của HTTPClient ** requestWithMethod: path: parameters: ** – onmyway133

Các vấn đề liên quan