使用HTTP Post方法如何在iphone中创建登录页面

我已经创建了一个Login视图。 每次登录时都会显示登录成功消息。 即使我输入错误的用户名和密码。我创建了登录页面静态。被提取的链接是示例Web服务链接。 这是我现在正在使用的方法:请给我任何想法。谢谢。

loginPage.m 

 (IBAction)login:(id)sender { NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"HTTP://URL"]]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; [request setHTTPBody:postData]; NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; if (conn) { NSLog(@"connection successful"); } else { NSLog(@"Failed"); } } -(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { } -(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [receivedData setLength:0]; // NSURL *theURL=[response URL]; } -(void) connectionDidFinishLoading:(NSURLConnection *)connection { if(receivedData) { NSLog(@"success",[receivedData length]); } else { NSLog(@"Success",[receivedData length]); } } 

 NSString *string= [NSString stringWithFormat:@"your Url.php?&Username=%@&Password=%@",username,password]; NSLog(@"%@",string); NSURL *url = [NSURL URLWithString:string]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSURLResponse *response; NSError *err; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; NSLog(@"responseData: %@", responseData); NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"responseData: %@", str); NSString *str1 = @"1"; if ([str isEqualToString:str1 ]) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Successfully" message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [alert show]; } else { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Try Again" message:@"" delegate:self cancelButtonTitle:@"Try Later" otherButtonTitles:@"Call", nil]; alert.tag = 1; [alert show]; } 

不需要使用JSON,你可以在没有JSON的情况下做到这一点!

 - (void) alertStatus:(NSString *)msg :(NSString *)title { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [alertView show]; } - (IBAction)loginClicked:(id)sender { @try { if([[txtUserName text] isEqualToString:@""] || [[txtPassword text] isEqualToString:@""] ) { [self alertStatus:@"Пожалуйста заполните все поля!!!" :@"Авторизация не удолась!"]; } else { NSString *post =[[NSString alloc] initWithFormat:@"login=%@&pass=%@",[txtUserName text],[txtPassword text]]; NSURL *url=[NSURL URLWithString:@"http:xxxxxxxx.xxx/?"]; NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSError *error = [[NSError alloc] init]; NSHTTPURLResponse *response = nil; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if ([response statusCode] >=200 && [response statusCode] <300) { NSData *responseData = [[NSData alloc]initWithData:urlData]; NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; if([jsonObject objectForKey:@"error"]) { [self alertStatus:@"" :@""]; } else { [self alertStatus:@"" :@""]; } } else { if (error) NSLog(@"Error: %@", error); [self alertStatus:@"Connection Failed" :@"Login Failed!"]; } } } @catch (NSException * e) { NSLog(@"Exception: %@", e); [self alertStatus:@"Login Failed." :@"Login Failed!"]; } [txtUserName resignFirstResponder]; [txtPassword resignFirstResponder]; } 

试试下面的代码。

 -(void)webservice_Call { NSString *urlString=@"http://api.openweathermap.org/data/2.1/find/city?lat=10.369&lon=122.5896"; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10]; [request setHTTPMethod: @"GET"]; NSError *requestError; NSURLResponse *urlResponse = nil; NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError]; NSDictionary *resDictionary = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingMutableContainers error:Nil]; } 

iOS 9版本的发布方法

  NSMutableDictionary *post = [[NSMutableDictionary alloc]init];  [post setValue:@“25” forKey:@"user_id"]; NSArray* notifications = [NSArray arrayWithObjects:post, nil];      NSError *writeError = nil;      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];      NSString *postLength = [NSString stringWithFormat:@"%d",[jsonData length]];      NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];     [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://your/url]]];     [request setHTTPMethod:@"POST"];     [request setValue:postLength forHTTPHeaderField:@"Content-Length" ];     [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];     [request setHTTPBody:jsonData];     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; // Create a data task object to perform the data downloading.   NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {    data = [[NSData alloc]initWithData:urlData];    NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; }];     [task resume]; 
 -(void)apiCode { NSString *string= [NSString stringWithFormat:@"http:url...project_id=1&user_id=58&question=%@&send_enquiry=%@",self.txtTitle.text,self.txtQuestion.text]; NSLog(@"%@",string); NSURL *url = [NSURL URLWithString:string]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSURLResponse *response; NSError *err; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; NSLog(@"responseData: %@", responseData); NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"responseData: %@", str); NSString *str1 = @"success"; if ([str isEqualToString:str1 ]) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Successfully" message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [alert show]; } else { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Try Again" message:@"" delegate:self cancelButtonTitle:@"Try Later" otherButtonTitles:@"Call", nil]; alert.tag = 1; [alert show]; } }