2013-06-04 59 views
3

我試圖通過使用以下代碼發出https發佈請求。IOS中的HTTPS發佈請求

NSURL *url = [NSURL URLWithString:@"https://portkey.formspring.me/login/"]; 

//initialize a request from url 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url  standardizedURL]]; 

//set http method 
[request setHTTPMethod:@"POST"]; 
//initialize a post data 

NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"username", @"username", 
          @"password", @"password", nil]; 

NSError *error=nil; 

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postDict 
                options:NSJSONWritingPrettyPrinted  error:&error]; 



[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

//set post data of request 
[request setHTTPBody:jsonData]; 

//initialize a connection from request 
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

//start the connection 
[connection start]; 

但即時得到以下響應。

錯誤錯誤域= NSURLErrorDomain代碼= -1202「此服務器的證書無效。您可能正在連接到一個僞裝成是服務器‘portkey.formspring.me’,它可以把您的機密信息風險。」 UserInfo = 0x7564180 {NSLocalizedRecoverySuggestion =你想連接服務器嗎?NSErrorFailingURLKey = https://portkey.formspring.me/login/,NSLocalizedDescription =這個服務器的證書是無效的。您可能正在連接到假裝爲「portkey.formspring.me」的服務器,這可能會將您的機密信息置於危險之中。,NSUnderlyingError = 0x7168a20「此服務器的證書無效。您可能正在連接到服務器僞裝成「portkey.formspring.me」,它可以把您的機密信息處於危險之中。「,NSURLErrorFailingURLPeerTrustErrorKey =}

任何人能告訴我如何使用NSURLConnection的進行POST請求?

在此先感謝。

+1

我認爲你需要解決它在服務器端 –

+0

錯誤回答你的問題,服務器不是他們所說的人(就iOS而言) – KevinDTimm

+0

他們的證書e已經過期了一段時間,所以我認爲他們知道這一點。你確定你連接到正確的URL? –

回答

7

您嘗試連接的網站證書不可信(請嘗試訪問您在Chrome中發佈的鏈接)。

默認情況下,iOS不會讓您連接到呈現不受信任證書的網站。如果絕對必要,您可以繞過此檢查 - 請參閱此問題:How to use NSURLConnection to connect with SSL for an untrusted cert?

但是,實際修復問題的方式會更好,更好。

0

NSURLConnection這些委託方法是棄用

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
-(void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 

可以使用-connection:willSendRequestForAuthenticationChallenge:,而不是這3種棄用方法

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) 
    { 
     [[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] forAuthenticationChallenge:challenge]; 
    } 
}