2014-03-14 58 views
1

下面的代碼是簡單登錄應用程序。我使用Post請求傳遞用戶名和密碼來獲取詳細信息。但是我得到@「」來自web服務的響應。使用帶網關保護的JSON Webservice時IOS無響應

email= emailTextField.text; 
password=passwordTextfield.text; 

NSString *post = [[NSString alloc] initWithFormat:@"UserName=%@&Password=%@",email,password]; 

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 

NSURL *url = [NSURL URLWithString:@"http:Gateway/api/json"]; 
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; 
[theRequest setHTTPMethod:@"POST"]; 
[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[theRequest setHTTPBody:postData]; 
[theRequest setHTTPBody:postData]; 

NSURLResponse *response;// = [[NSURLResponse alloc] init]; 

NSError *error;// = [[NSError alloc] init; 

NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error]; 

NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; 

NSLog(@"Login response: is %@",str); 
+0

考查['NSURLConnectionDelegate'](https://developer.apple.com/library/mac/documentation/Foundation/Reference /NSURLConnectionDelegate_Protocol/Reference/Reference.html)提供身份驗證的方法。 – Amar

+0

我應該通過哪種方法來傳遞用戶名和密碼憑據? – iOSDeveloper

+0

NSLog(@「errot:%@」,錯誤); –

回答

2

爲了提供認證證書給服務器使用NSURLConnection的委託

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 

    if ([challenge previousFailureCount] == 0) { 

     NSURLCredential *credential; 
     credential = [NSURLCredential credentialWithUser:userName password:password persistence:NSURLCredentialPersistenceNone]; 
     [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 
    } else { 
     [[challenge sender] cancelAuthenticationChallenge:challenge]; 
    } 
} 
+1

很好的解決方案.... – svmrajesh