-5
NSString *data = [NSString stringWithFormat:@"username=%@&password=%@",usertxt.text,pwdtxt.text,[NSNumber numberWithBool:YES]];
    NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

// 准备发送数据的 URL 请求。

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString *url = [NSString stringWithFormat:URL_PATH];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
[request setTimeoutInterval:7.0];

NSURLResponse *_response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

//打印服务器响应

NSLog(@"Login response:%@",str);

//将JSON字符串解析成NSDictionary

 NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlData
                                                     options:kNilOptions
                                                      error:&error]; 
4

1 回答 1

5

Try This
不需要使用 JSON 只需尝试此代码即可从服务器获取响应

NSString *string= [[NSString alloc]initWithFormat:@"url"];
        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];
        }

如果您的响应字符串success不是把它放在@"1"

于 2013-08-16T05:35:13.503 回答