【问题标题】:How can my iphone app send data to the server's php file?我的 iphone 应用程序如何将数据发送到服务器的 php 文件?
【发布时间】:2012-02-09 17:55:08
【问题描述】:

以下是我在服务器中的目标 php 文件的开头部分。

$xmlFile = file_get_contents("php://input");
echo $xmlFile."<br>";

很遗憾,浏览器的该页面上没有打印任何内容。

以下是我iphone端编程的一部分

NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/target.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content- Type"];

NSMutableData *xmlData = [NSMutableData data];
[xmlData appendData: [[NSString stringWithFormat: @"<?xml version=\"1.0\"   encoding=\"UTF-8\" ?>"] dataUsingEncoding: NSUTF8StringEncoding]];
[xmlData appendData: [[NSString stringWithFormat: @"<Packet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance iphone_schema.xsd\" xmlns=\"http://www.mywebsite.com/iphone.xsd\">"] dataUsingEncoding: NSUTF8StringEncoding]];
[xmlData appendData: [[NSString stringWithFormat: @"<info1>%@<info1>",self.uuid] dataUsingEncoding: NSUTF8StringEncoding]];

//....append xml data strings in the same way
[request setHTTPBody:xmlData];
NSURLConnection *connect = [NSURLConnection connectionWithRequest:request delegate:self];
if(connect != nil){
    NSLog(@"valid request");
}

连接对象不是零。但我不确定应用程序是否已将请求 POST 消息发送到 php 页面。

我在那个 php 文件中写了一些代码来测试连接。似乎没有从 iphone 收到任何信息。那么发生了什么?我已经测试了几个小时!
希望可以有人帮帮我!谢谢!

【问题讨论】:

    标签: php iphone http post


    【解决方案1】:

    设置您的NSURLConnection delegate methods。这将帮助您更好地诊断问题并查看它是在 iPhone 端还是服务器端。

    另外,如果您发送 POST 请求。所以你不需要从 PHP 的输入流中读取。使用$_POST super global

    您还可以通过从命令行发送请求来确保您的 PHP 脚本正确无误。例如,*nix 上的 curl

    【讨论】:

      【解决方案2】:

      $xmlFile = file_get_contents("php://input"); echo $xmlFile."
      ";

      这只会在您从发布到输入的浏览器中查看时才会回显某些内容,如果您的 iOS 发布到 PHP 然后您之后访问 PHP,则不会发生这种情况。

      通常您根本无法通过这种方式对其进行验证。您必须在 PHP 中设计一个响应并设置您的委托方法来处理 PHP 返回的任何内容。

      如:

      $xmlFile = file_get_contents("php://input");
      if ($xmlFile) {
      echo "{\"file\":\"$xmlFile\"}";
      }
      

      通过这种方式,您可以使用 NSJSONSerializer 解码 iOS 中的响应,并查看您发布的内容与返回的内容相同。 }

      【讨论】:

        【解决方案3】:

        试试 ngrep。这可能会有所帮助。

        首先尝试设置homebrew

        然后做一个

        brew install ngrep
        

        然后

        sudo ngrep host mywebsite.com port 80
        

        这应该会显示设备和 mywebsite.com 上的服务器之间发送和接收的数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-16
          • 1970-01-01
          • 2011-11-28
          • 2023-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多