php - mysql + json + iphone + 网络服务

标签 php ios json web-services

我已经在 php 中创建了网络服务。

现在我想在我的 iOS 应用程序中调用该 Web 服务。

我正在使用 JSON 解析来获取数据。

但它向我显示了一些错误。

我的代码:

    SBJSON *json = [SBJSON new];
    json.humanReadable = YES;
    responseData = [[NSMutableData data] retain];

    NSString *service = @"/getLastUpdated";
    NSString *str;
    str = @"LastUpdated";


    NSString *requestString = [NSString stringWithFormat:@"{\"LastUpdated\":\"%@\"}",str];

   // [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"WRONGANSWER"];

    NSLog(@"request string:%@",requestString);
    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];


    NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"];
    NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
    NSString *urlLoc = [fileContents objectForKey:@"URL"];
    urlLoc = [urlLoc stringByAppendingString:service];
    NSLog(@"URL : %@",urlLoc);

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: 
                                    [NSURL URLWithString: urlLoc]];  
    NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];
    [request setHTTPMethod: @"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody: requestData];

    NSError *respError = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];


    if (respError) 
    {
        //        NSString *msg = [NSString stringWithFormat:@"Connection failed! Error - %@ %@",
        //                         [respError localizedDescription],
        //                         [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; 
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sing It Say It" 
                                                            message:@"check your network connection" delegate:self cancelButtonTitle:@"OK" 
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];

    } 
    else
    {
        NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

        NSDictionary *results = [responseString JSONValue];
        NSLog(@"results=%@",results);
        NSString *extractUsers = [results objectForKey:@"d"];

        // NSDictionary *finalResult = [extractUsers JSONValue];
        NSLog(@"Final Result : %@",extractUsers);
        [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"NAVIGATION"];
        [[NSUserDefaults standardUserDefaults] setValue:extractUsers forKey:@"NEWQUEID"];
    }

错误:

2012-09-24 16:08:47.090 ACTEC_Webservice[3239:f803] -JSONValue failed. Error trace is: (
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x6865bc0 {NSLocalizedDescription=Unrecognised leading character}"
)
2012-09-24 16:08:47.091 ACTEC_Webservice[3239:f803] results=(null)
2012-09-24 16:08:47.092 ACTEC_Webservice[3239:f803] Final Result : (null)

在响应字符串日志中显示这个值:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>404 - File or directory not found.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>404 - File or directory not found.</h2>
  <h3>The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.</h3>
 </fieldset></div>
</div>
</body>
</html>

请帮帮我.. 谢谢。

最佳答案

行:

NSDictionary *results = [responseString JSONValue];

抛出异常,因为 responseString 不是 json。它是 HTML。您需要阅读 HTML 以发现错误:

<h2>404 - File or directory not found.</h2>
<h3>The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.</h3>

看来您的 URL 有误。

太糟糕了,尽管 JSONValue 失败得如此不优雅。如果确实如此,您将希望在生产代码中提供一些保护措施。在尝试解析之前以某种方式验证 json,或者实现异常处理程序。

关于php - mysql + json + iphone + 网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12563364/

相关文章:

php - 使用 PHP 将数据添加到特定列中的 csv 文件

ios - Swift 内容标签?

ios - View Controller 的 View 属性

sql - 从 SQL Server 中以字典(字符串索引列表)表示法输出 json

java - 将具有动态键的 json 对象映射到 java 对象

php - SQL ERROR = 'Backpack' 中的未知列 'where clause' ...提示?

php - 使用 PDO 和 PHP 函数选择数据

python - 如何在 python 中解码无效的 json 字符串

php - 如何使用 phpseclib 设置自定义 SFTP 端口

ios - 使用夜间版本的 MobileVLCKit 时架构 arm64 的 undefined symbol