使用iOS应用程序中的Post发送到服务器上的PHP文件

时间:2014-02-12 06:13:10

标签: ios iphone

我使用以下代码发送数据到服务器上的php文件

     NSString *post =[[NSString alloc] initWithFormat:@"UserName=%@&UserPassword=%@",appDelegate.userName,appDelegate.userPassword];

     NSLog(@"post is %@",post);


     NSURL *url=[NSURL URLWithString:@"http://ec2-50-94-162-129.compute-1.amazonaws.com/usercredential.php?"];

     NSLog(@"URL is %@",url);



    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];



    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];


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

    NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];


    NSLog(@"%@",data);

    data = [data stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"%@",data);

如果我直接从浏览器访问文件并在地址中提供userNAme,则显示登录失败然后它可以正常工作从iPhone应用程序无效

0 个答案:

没有答案