ios - 在 iOS 上发送 HTTP POST 请求并从服务器接收响应

标签 ios objective-c iphone nsurlconnection

我正在尝试从服务器获取连接并接收来自服务器的响应,但我无法理解响应代码。

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"_username",@"_password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://<MY_URL>"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
if(conn) {
    NSLog(@"Connection Successful");
} else {
    NSLog(@"Connection could not be made");
}

这是否正确,因为我没有收到回复。??

现在响应代码是什么????

NSURLResponse *response=nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(@"%@",response);
if (response) {
  //UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
  //TableViewController *obj=[story instantiateViewControllerWithIdentifier:@"table1"];
  UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Login success" message:@"correct Username or Password" delegate:self cancelButtonTitle:@"Done" otherButtonTitles: nil];
  [alert show];
  //[self.navigationController pushViewController:obj animated:YES];
}
else
{
  UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Login Failure" message:@"Incorrect Username or Password" delegate:self cancelButtonTitle:@"Done" otherButtonTitles: nil];
  [alert show];
}

最佳答案

您需要获取该数据:

NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if(responseData)  { 
    NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments  error:&error];
    NSLog(@"res---%@", results);
}

并使用字典以供进一步使用。

关于ios - 在 iOS 上发送 HTTP POST 请求并从服务器接收响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35174943/

相关文章:

ios - 等到对象可用

ios - 将文本和图像放在 AttributedString 中

ios - 将大数据转换为 NSData

iphone - 将数据加载到核心数据模式中

ios - 错误 : could not find included file 'Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig' in search paths (in target 'Runner' )

iphone - UITableView/UITableViewCell 点击事件响应?

iphone - Objective-C 中的 SSLv3 通信

iphone - 如何使用 [self.view addSubview : myView] where myView is subclass of UIView? 添加 subview

javascript - 使用 ajax 加载字典文件,不要让 iPhone Mobile Safari 崩溃

ios - 了解 iOS 中的 View 层次结构