PHP编写简单的App接口

2019-05-03 04:07:36刘景俊

PHP POST接口

假设我们要求传参数type过来,而且要求是数值型,用于返回不同的数据,当我们做接口测试时,就可以通过这么来干,就不需要等后台给接口了!

<?php
 
$type = $_POST['type'];
$data = '';
 
if (isset($type) && is_numeric($type) && $type >= 0) {
  if ($type == 1) {
    $data = array(
      'type' => $type, 
      'name' => '标哥的技术博客',
      'site' => 'www.huangyibiao.com');
  } else if ($type == 2) {
    $data = array(
      'type' => $type, 
      'name' => '公众号:标哥的技术博客',
      'site' => 'weixin search: biaogedejishuboke');
  } 
 
  $response = array(
    'code'  => 200, 
    'message' => 'success for request',
    'data'  => $data,
    );
 
  echojson_encode($response);
  return;
} 
 
$response = array(
  'code'  => 999, 
  'message' => 'argument error for request',
  'data'  => $data,
  );
 
echojson_encode($response);

iOS调POST接口

下面是iOS客户端如何调用刚才所写的PHP POST接口,其中使用了HYBNetworking笔者的这个开源库:

NSString *url = @"http://www.api.com/index.php";
NSDictionary *params = @{@"type" : @(1)};
[HYBNetworkingpostWithUrl:urlrefreshCache:YESparams:paramssuccess:^(id response) {
  
}fail:^(NSError *error) {
  
}];

我们看看效果如下,可看到如愿地接收到了服务器返回的接口数据并解析出来了:

小结

本篇就到此为止吧,相信大家若想学习它,一定会认真去操作一遍的!其实写下本篇文章之前,笔者也从尝试过!

今后会慢慢接触它,慢慢掌握它,一定会让你在工作上更加顺利的!

相关文章 大家在看