我試圖發送用戶名和密碼到通常通過表單完成的網站。然而,服務器將我重定向到登錄頁面,通常在用戶名和密碼錯誤時發生。用戶名是電子郵件地址的形式,密碼是一個字符串。將發佈變量發送到iOS表格
由於開發者不在,我目前可以訪問該網站以檢查值是否正確處理。任何人都可以在下面創建的代碼中看到任何明顯的錯誤?
請注意我已經從示例代碼中刪除了URL,以保護隱私。
// Validate login
-(bool)validateLogin{
// Initialize URL to be fetched
NSURL *url = [NSURL URLWithString:@"removedurl"];
NSString *post = @"username=example1%40example.com&password=example2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
// Initalize a request from a URL
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set url
[request setURL:url];
//set http method
[request setHTTPMethod:@"POST"];
//set request length
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//set request content type we MUST set this value.
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//set post data of request
[request setHTTPBody:postData];
NSLog(@"%@", [request allHTTPHeaderFields]);
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_connection = connection;
//start the connection
[connection start];
return YES;
}
我爲此NSURLResponse * theResponse = [[ NSURLResponse alloc] init]; NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error]; NSHTTPURLResponse * httpResp =((NSHTTPURLResponse *)theResponse); –
這種連接模式不太正確:您不要將委託設置爲NSURLConnection對象,以便捕獲回調。並且'[連接開始]'不是必需的。 – pbibergal
請參閱我的答案中的編輯。 – pbibergal