我想使用简单的登录使用JSON和Web服务。使用网关用户名和密码阻止Web服务。需要哪些代码才能将用户名和密码传递给网关?这是为什么发生?我得到一个响应代码为0。此外,如果有人可以提供一个很好的教程,了解有关Web服务和JSON在iOS中。提前致谢。连接失败JSON流解析在IOS
这是我的代码。代码写入UIButton
NSString *post = [NSString stringWithFormat:@"&Email=%@&Password=%@",
[self.emailTextField text], [self.passwordTextfield text]];
NSLog(@"PostData: %@",post);
NSURL *url = [NSURL URLWithString:@"http:/Gateway/api/json/reply/ZympayAuthenticateCustomer"];
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/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSLog(@"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSString *responseData = [[NSString alloc]initWithData:urlData
encoding:NSUTF8StringEncoding];
NSLog(@"Response ==> %@", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(@"Data: %@",jsonData);
NSLog(@"Success: %ld",(long)success);
if (success == 1) {
NSLog(@"Login SUCCESS");
}
else {
NSString *error_msg = (NSString *) jsonData[@"error_message"];
[self alertStatus:error_msg :@"Sign in Failed!" :0];
}
}
else {
//if (error) NSLog(@"Error: %@", error);
[self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
}
}
}
@catch (NSException * e)
{
NSLog(@"Exception: %@", e);
[self alertStatus:@"Sign in Failed." :@"Error!" :0];
}
if (success)
{
NSLog(@"THIS IS SUCCESS");
// [self performSegueWithIdentifier:@"login_success" sender:self];
}
}
为什么你发送的内容为'应用程序/ x-WWW的形式,urlencoded'?这通常很容易出错,并且您没有正确传递参数(忽略适当的百分比编码)。无论如何,使用** JSON **作为你的内容类型。 – CouchDeveloper