代码之家  ›  专栏  ›  技术社区  ›  iOSDeveloper

连接失败,IOS中的JSON流解析失败

  •  1
  • iOSDeveloper  · 技术社区  · 12 年前

    我正在尝试使用简单登录 JSON和Web服务 。使用网关用户名和密码阻止web服务。向网关传递用户名和密码需要包含哪些代码?为什么会发生这种情况?我得到的响应代码为0。如果有人能提供一个很好的教程来学习web服务和 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];
        }
    }
    
    2 回复  |  直到 12 年前
        1
  •  1
  •   Rajesh Loganathan Andrey    12 年前

    试试这个

    NSURL*URL=[NSURL URLWithString:@“ http://www.site.com/test_json_link/?username= “用户名”&password='password'“];

    现在,为了防止我的web服务器重定向到登录页面。我创建了一个中间件来处理上述url。我的定制中间件包含以下内容:

    if request.path != '/accounts/login/' and request.user.is_anonymous():
         url = request.path.split('/')[1]
         if url == 'test_json':
             username = request.GET['username']
             password = request.GET['password']
             user = authenticate(username = username, password = password)
             if user is not None:
                 if user.is_active:
                     login(request, user)
    
        2
  •  0
  •   CouchDeveloper    12 年前

    代码中存在许多问题。

    唯一一个让你的方法很可能失败的原因是你使用 NSURLConnection 方便分类法 sendSynchronousRequest: :如果请求需要身份验证,则必须在URL中传递凭据。

    另请参见: sendSynchronousRequest:returningResponse:error:

    此外,当请求被重定向时,您无法取消请求并采取适当的操作。

    因此,您的方法的第一个重大变化是使用 NSURL连接 s的委托方法,或可能使用 NSURLSession NSURLSessionTask 。在SO上有很多解决方案,可以让您快速开始实施自己的解决方案。

    然而,建议的解决方案是使用第三方库。