POST调用不会将REST API的结果返回给iPhone App

时间:2012-04-10 14:37:01

标签: php iphone api rest

我无法让iPhone App正确地使用我的API发送POST。进行调用时,根本不会返回任何结果。

  1. POST调用旨在发送消息(存储消息,检查某些参数,并启动'推送'通知)

  2. 后调用可以从.php文件中的表单开始,但不能通过应用程序使用。 返回结果:{“message”:{“message”:{“saved”:1}},“push”:1,“error”:[]}推送期间的错误是预期的,因为test2.php没有发送消息到移动设备,只是数据库。

  3. 以下是该应用的POST代码

    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *time = [dateFormatter stringFromDate:now];
    NSLog(@"time : %@", time);
    NSLog(@"message : %@", self.messageTxt.text);
    
    NSString *urlString = [[Utils getSendMessageUrl] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[UserSession sharedInstance].customerTableNum forHTTPHeaderField:@"point"];
    [request setValue:[UserSession sharedInstance].locationId forHTTPHeaderField:@"location"];
    [request setValue:time forHTTPHeaderField:@"sent"];
    [request setValue:self.messageTxt.text forHTTPHeaderField:@"message"];
    [request setValue:[UserSession sharedInstance].phoneNumber forHTTPHeaderField:@"number"];
    
    self.receivedData = [NSMutableData data];
    NSURLConnection *sendConnection = [NSURLConnection connectionWithRequest:request delegate:self];
    [sendConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [sendConnection start];
    
  4. 什么可能导致应用加载index.php没有结果? post变量设置正确,即使'push'失败,仍应将消息输入数据库(因为test2.php成功完成)。

    提前感谢您的任何见解。

    -----------编辑----------------

    以下是我的应用开发者的回复:

    pragma mark - NSURLConnection delegate
    
    
      (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
     {
         NSLog(@"didReceiveResponse");
         [self.receivedData setLength:0];
     }
    
     (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
     {
         NSLog(@"didReceiveData : %@", data);
         [self.receivedData appendData:data];
      }
    
      (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
     {
          NSLog(@"didFailWithError");
     }
    
      (void)connectionDidFinishLoading:(NSURLConnection *)connection
     {
         NSString *resultString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
         NSLog(@"result : %@", resultS tring);
    
          [self performSelectorOnMainThread:@selector(didSendMessage:) withObject:resultString waitUntilDone:NO];
      }
    
    
    I get the following log.
    
        2012-04-11 00:13:59.177 M[7682:707] didReceiveResponse
    
        2012-04-11 00:13:59.179 M[7682:707] result : 
    
        No header response is sent back.
    

    请求需要以下内容:

    • 位置(号码)
    • point(number)
    • 号码(号码)
    • message(string)
    • 已发送(日期时间:yyyy-MM-dd HH:mm:ss)

    这是一个PHP代码,没有安全部分来减少长度。

    1. 从case = post开始处理所有内容的调用(get用于检索邮件)

      $request = RestUtils::processRequest();
      
      switch ($request->getMethod()){
          case 'get':
          case 'post':
              $db = get_db();
              $response = array();
              $response["message"] = array();     
              $data = $request->getRequestVars();
              $location = htmlspecialchars($data["location"]);
              $point = htmlspecialchars($data["point"]);
              $area = get_area($point, $location, $db);
              $employee = get_employee($request, $area, $db);
              $message_id = add_message($response["message"], $request, $area, $db);      
              if($employee == false){
                  $response["error"] = "mo.";
                  $response["pushed"] = 0;
                  RestUtils::sendResponse(410, json_encode($response), 'application/json');
                  exit;
              }
              $response["pushed"] = array();
              $response["error"] = array();
              $number = htmlspecialchars($data['number']);
              switch($employee["phone_Type"]){
                  case 1:
                      if(is_blocked($number)){
                          $response["error"] = "You're Number is Blocked";
                          $response["pushed"] = 0;
                          RestUtils::sendResponse(503, json_encode($response), 'application/json');
                          exit;
                      }
                      if(push_android($employee["device_ID"], $message_id, $point, $location) == false){
                          $response["error"] = "Service Temporally Unavailable";
                          $response["pushed"] = 0;
                          RestUtils::sendResponse(400, json_encode($response), 'application/json');
                          exit;
                      }
                      $response["pushed"] = 1;
                      break;
                  case 2:
                      if(is_blocked($number)){
                          $response["error"] = "You're Number is Blocked";
                          $response["pushed"] = 0;
                          RestUtils::sendResponse(503, json_encode($response), 'application/json');
                          exit;
                      }
                      push_iOS($employee["device_ID"], $message_id, $point, $location);
                      $response["pushed"] = 1;
                      break;
                  default:
                      $response["pushed"] = 0;
                      $response["error"] = 'Unsupported Phone Type';
                      RestUtils::sendResponse(406, json_encode($response), 'application/json');
              }
              $db->close();
              RestUtils::sendResponse(200, json_encode($response), 'application/json');
              break;
      }
      
    2. 以下是支持功能:

      function build_post_query($area, $point, $location, $message, $number, $sent){
          return "INSERT INTO messages (message_ID, area_ID, point_ID, location_ID, message_Sent, message_Text, message_Number, message_Viewed) VALUES (NULL, ".$area.", ".$point.", ".$location.", '".$sent."', '".$message."', '".$number."', 0)";
      }
      
      function add_message(&$response, $request, $area, $db){
          $data = $request->getRequestVars();
          $point = htmlspecialchars($data["point"]);
          $location = htmlspecialchars($data["location"]);
          $area = get_area($point, $location, $db);
          $sent = htmlspecialchars($data["sent"]);// 'yyyy-mm-dd HH:mm:ss' format from users phone
          $message = htmlspecialchars($data["message"]);
          $number = htmlspecialchars($data["number"]);
          $query = build_post_query($area, $point, $location, $message, $number, $sent);
          $result = $db->query($query);
          $response["message"] = array('saved'=>$db->affected_rows);
          $message_id = $db->insert_id;
      
          return $message_id;
      }
      
      function get_area($p, $loc, $db){
          $query = "SELECT area_ID FROM points WHERE point_ID = ".$p." AND location_ID = ".$loc;
          $result = $db->query($query);
          $result = $result->fetch_assoc();
      
          return $result["area_ID"];
      }
      
      function get_employee($request, $area, $db){
          $data = $request->getRequestVars();
          $point = htmlspecialchars($data["point"]);
          $location = htmlspecialchars($data["location"]);
          $query = "SELECT device_ID, phone_Type, employee_Phone FROM active_employees WHERE area_ID = ".$area." AND location_ID = ".$location;
          $result = $db->query($query);
          if($result->num_rows > 1){
              $employees = array();
              while($row = $result->fetch_assoc()){
                  array_push($employees, $row);
              }
              return $employees;
          }
          if($result->num_rows == 1){
              return $result->fetch_assoc();
          }
          return false;
      }
      

2 个答案:

答案 0 :(得分:0)

是否有可能记录应由php处理的请求?信息太低,无法在这里给出有意义的答案。

答案 1 :(得分:0)

我认为你得到的是一堆PHP代码,因为你发送的任何数据都没有插入数据库中。我认为可能有两个原因。

发送该数据时出现问题或接收数据存在问题

使用如下代码

的post方法
NSString *string=@"Your url";

NSURL *url = [NSURL URLWithString:string];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];

NSString *mpfBoundry = [NSString stringWithString:@"---------------------------"];
NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded; boundary=%@", mpfBoundry];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    NSString* body =[NSString stringWithFormat:@"column1=%@&column2=%@&column3=%@", data1,data2,data3];

[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc]initWithRequest:request delegate:self];

[connection start];