iOS不接受来自php web服务的json响应

时间:2013-01-18 20:50:12

标签: php objective-c web-services afnetworking

我是iOS的初学者。我有一个简单的Web服务,它从表中检索数据并以JSON格式发送结果。我试图从iOS与该Web服务进行通信以接收JSON响应但面临问题。这是我收到的错误:

Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected     content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html" UserInfo=0x7598e70

以下是我的代码段:

PHP Web服务:

$stmt = "SELECT STORE_TYPE, STORE_NAME FROM STORE WHERE STORE_ZIP = $zip";
$result = mysqli_query($this->databaseconnection, $stmt);  
$storelist = array();
$store = array();
$jsondata;
while ($row = mysqli_fetch_assoc($result)) {
  $store['STORE_TYPE'] = $row['STORE_TYPE'];
  $store['STORE_NAME'] = $row['STORE_NAME'];
  array_push($storelist,$store);
}
$jsondata = json_encode($storelist);
echo $jsondata;

当我从浏览器执行我的php时,我得到以下结果:

[{"STORE_TYPE":"GROCERY","STORE_NAME":"Walmart"},{"STORE_TYPE":"BAKERY","STORE_NAME":"Lanes Bakery"},{"STORE_TYPE":"GROCERY","STORE_NAME":"Copps"}]

与Web服务通信的iOS代码段:

NSURL *url = [NSURL URLWithString:@"http://localhost/~Sandeep/store/store.php?rquest=getstores&zip=53715"];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation  JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"%@", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];

我查看了很多教程,他们都说在php中的数组上执行'json_encode'会以JSON格式编码数据,而'echo'就是将编码的JSON作为响应发送的方式。出于某种原因,我的iOS并没有将其视为JSON。我不确定我在这里错过了什么/做错了。

我非常感谢您对此的投入。

谢谢!

1 个答案:

答案 0 :(得分:3)

您需要设置正确的内容类型(使用header),错误列出了可接受的类型,尽管您应该使用application/json

$stmt = "SELECT STORE_TYPE, STORE_NAME FROM STORE WHERE STORE_ZIP = $zip";
$result = mysqli_query($this->databaseconnection, $stmt);  
$storelist = array();
$store = array();
$jsondata;
while ($row = mysqli_fetch_assoc($result)) {
  $store['STORE_TYPE'] = $row['STORE_TYPE'];
  $store['STORE_NAME'] = $row['STORE_NAME'];
  array_push($storelist,$store);
}
$jsondata = json_encode($storelist);
header('Content-Type: application/json');
echo $jsondata;