2013-05-17 3 views
5

나는 최근에 CodeSchool course to learn iOS을 따라 갔고 AFNetworking을 사용하여 서버와 상호 작용하는 것이 좋습니다.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의 설명서를 확인했지만 거기에서 아무것도 유용하지 않았다.

이 요청에 대한 사용자 이름과 암호를 서버에 전달하려면 어떻게해야합니까?

답변

6

당신은 AFHTTPClient를 사용할 수 있습니다.

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에 매개 변수를 전달하는 것처럼 같은 방식으로 작성을하지만,에 대한 방법을 설정 POST 문자열을 URL의 ? 대신 HTTP 본문에 넣습니다. 대신 수동으로 작업을 생성하고 시작하는, AFHTTPClient를 서브 클래 싱하고 postPath:parameters:success:failure: 방법을 사용하는 것, 이상적으로

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

:

+0

예, HTTPClient ** requestWithMethod : 경로 : 매개 변수 : ** 장면 뒤로 – onmyway133