我是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 网络服务:
$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。我不确定我在这里错过了什么/做错了什么。
我非常感谢您对此的投入。
谢谢!