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

时间:2016-02-03 10:48:39

标签: 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://joomerang.geniusport.com/geniusport/api.php?json"]];
[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];
}

2 个答案:

答案 0 :(得分:1)

您需要获取该数据:

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);
}

并使用字典进一步使用。

答案 1 :(得分:0)

所有代码都是正确的,只需要在info.plist

中添加
  

应用传输安全设置

     
      
  • 允许任意载入
  •   

add red box content in your info.plist

相关问题