2012-05-25 3 views
0

PHP 스택에있는 REST API로 인증을받는 데 문제가 있습니다. 브라우저에서 작동하도록 로그인 할 수있는 쿼리 문자열은 http://foo.com/gamer/index.php?module=Login&action=myLogin ...와 같습니다. RestKit에서 사용 가능한 모든 설명서를 읽고 NSLogConfigure를 활성화하는 것 외에도 다음 코드를 작성했습니다. 코드 출력은 다음과 같습니다. 코드여러 매개 변수를 사용하는 RestKit 인증

- (void)sendHTTPAuthRequestWithParams { 
NSMutableDictionary* authParams = [[NSMutableDictionary alloc] init]; 
NSMutableDictionary* moreParams = [[NSMutableDictionary alloc] init]; 

//user and password params 
[authParams setObject:usernameTextField.text forKey:@"login"]; 
[authParams setObject:passwordTextField.text forKey:@"password"]; 

//more parameters for rest login api 
[moreParams setObject:@"Login" forKey:@"module"]; 
[moreParams setObject:@"mylogin" forKey:@"action"]; 
[moreParams setObject:authParams forKey:@"params"]; 

//parsing 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON]; 
NSError *error = nil; 
NSString *json = [parser stringFromObject:moreParams error:&error]; 

[RKClient sharedClient].authenticationType = RKRequestAuthenticationTypeHTTP; 

//if no error 
if(!error) {   
    RKLogConfigureByName("RestKit/Network", RKLogLevelTrace); 
    [[RKClient sharedClient] post:@"/index.php?" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self]; 
    RKLogConfigureByName("RestKit/Network", RKLogLevelTrace); 
}  
//[[RKClient sharedClient] post:@"/index.php?module=Login&action=mylogin" params:authParams delegate:self]; } 

RKLogConfigureByName() 출력

2012-05-24 19:59:09.513 GiantsGamer[57045:207] D restkit.network:RKRequest.m:435 Sending asynchronous POST request to URL http://www.foo.com/gamer/index.php. 
2012-05-24 19:59:09.514 GiantsGamer[57045:207] T restkit.network:RKRequest.m:381 Prepared POST URLRequest '<NSMutableURLRequest http://localhost/gamer/index.php>'. HTTP Headers: { 
"Content-Length" = 85; "Content-Type" = "application/json";}. HTTP Body: {"module":"Login","action":"mylogin","params":{"login":"admin","password":"admin"}}. 2012-05-24 19:59:09.736 GiantsGamer[57045:207] D restkit.network:RKResponse.m:195 NSHTTPURLResponse Status Code: 200 2012-05-24 19:59:09.737 GiantsGamer[57045:207] D restkit.network:RKResponse.m:196 Headers: {"Cache-Control" = "no-store, must-revalidate"; 
    Connection = "Keep-Alive"; 
    "Content-Length" = 2745; 
    "Content-Type" = "text/html; charset=utf-8"; 
    Date = "Fri, 25 May 2012 02:59:09 GMT"; 
    Expires = ""; 
    "Keep-Alive" = "timeout=5, max=100"; 
    Pragma = ""; 
    Server = "Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8r DAV/2 PHP/5.3.8"; 
    "Set-Cookie" = "PIWIK_SESSID=a065dba239819175689b1e2a23021d01; path=/; HttpOnly"; 
    "X-Frame-Options" = sameorigin; 
    "X-Powered-By" = "PHP/5.3.8"; 
} 
2012-05-24 19:59:09.737 GiantsGamer[57045:207] T restkit.network:RKResponse.m:203 Read response body: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> 
<head>… 
</head> 
<body>... 
</body> 
</html> 

로그에서 볼 수 있듯이이 쿼리 문자열 (인증 매개 변수)는 HTTP 본문에 포함되어 있습니다. 괜찮습니까? 또한 http 응답 상태 코드 200 (OK)이 표시되지만 index.html의 웹 페이지에서 생성 된 전체 HTML 코드가 표시됩니다. 내가 어디로 잘못 가고 있는지 확실하지 않니? RestKit 응답을 어떻게 해독합니까?

+0

모든 매개 변수를 경로 변수에 간단한 문자열로 보내 봤습니까? 당신은 그걸 어떻게 대답합니까? – clopez

+0

나는 그 일을 시도했지만 괜찮 았는데 ... 그러나 인증 값을 하드 코딩해야했습니다. – rajeshvenkat

답변

1

모듈 및 동작을 GET 대신 POST 값으로 보내므로 코드가 작동하지 않습니다. params없이 index.php를 요청할 때와 같은 html 코드를 받고있을 것입니다. 원한다면 코드를 시험해보고 전체 HTML 응답을 캡쳐하고 웹에서 index.php HTML 응답과 비교할 수 있습니다. 매개 변수 없이도 동일 할 것입니다.

이 코드를 테스트하지만 한번 시도해하지 않은 : 당신이을 NSData를 얻을 것이다 당신이 응답에 JSON을 기대한다면이 함께있는 NSDictionary 해당 변환 할 수 있습니다 응답 본문에

- (void)sendHTTPAuthRequestWithParams { 

    NSString *loginPath = [NSString stringWithFormat:@"index.php?module=%@&action=%@",@"Login",@"myModule"]; 

    NSMutableDictionary* authParams = [[NSMutableDictionary alloc] init]; 
    [authParams setObject:usernameTextField.text forKey:@"login"]; 
    [authParams setObject:passwordTextField.text forKey:@"password"]; 

    [[RKClient sharedClient] post:loginPath usingBlock:^(RKRequest *request) { 
     request.authenticationType = RKRequestAuthenticationTypeHTTP; 
     request.method = RKRequestMethodPOST; 
     request.params = authParams; 
     request.delegate = self; 
     request.onDidLoadResponse = ^(RKResponse *response){ 
      if (response.statusCode > 299) { 
       //We got an error! 
      }else { 
       //Check Response Body to get Data! 
      } 
     }; 

    }]; 
} 

: 일을,

이 당신은 다른 방법을 볼 수 있습니다

, 좀 더 고급 : NSData to NSDictionary from JSON

RK의 주요 단점은 그것이 좋은 문서에 부족이다, 여기 당신이 몇 가지 기본 사항을 이해하고 볼 수있는 몇 가지 있습니다 RKObjectM을 사용하여 원하는 것 RestKit : Making a post to API with RKParams and mapping the response with RKObjectMapping using RestKit으로 꾸미기.

마지막으로, 당신은 또한이 코드를 확인할 수 있습니다, 그것은에 Do a simple json POST using RESTKit

은 또한 당신이 트위터에 RestKit의 개발자에게 문의 할 수있는 방법에 대해 설명합니다. 그게 나를 위해 큰 일을했습니다, 그들은 정말 빨리 대답!.

+0

고마워, @ clopez,이 완벽하게 나를 위해 일했습니다. 나는 원래의 코드 조각이 왜 작동하지 않는지에 대해 조금 당황 스럽다. 그래, 나는 또한 RKObjectMapping이 고급 쿼리에서 작동해야한다고 생각한다. – rajeshvenkat

+0

답변에 대한 답변을 업데이트하고, 원할 경우 최대 답변을 기억하십시오 :) – clopez

+0

후속 질문을 할 수 있습니까? NSMutableDictionary에 다중 양식, 이미지를 어떻게 포함합니까? http://stackoverflow.com/questions/11189120/include-image-using-nsmutabaledictionary-with-rkclient-and-receiving-on-the-php/11190451#comment14704769_11190451 – ruelluna

관련 문제