2016-02-03 146 views
0

收到一个性反应,我想从服务器连接并接收来自服务器的响应,但我不明白的响应代码。发送一个HTTP POST请求,并从服务器上的iOS

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]; 
} 
+0

什么是'NSLog'的结果呢? – yageek

+0

连接成功 –

+0

我meaned这个'的NSLog(@“%@”,响应);' – yageek

回答

0

所有的代码是正确的,你只需要添加这在你的info.plist

App Transport Security Setting

  • Allow arbitrary Loads

add red box content in your info.plist

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

,并使用字典继续使用。

+0

**的NSLog(@ “%@” ,responseData1); **为空 –

+0

任何错误是否意味着你可以检查NSError是否为零或什么? –

+0

没有错误,但当我检查responseData1输出为空 –