【问题标题】:iPhone POST to PHP failingiPhone POST 到 PHP 失败
【发布时间】:2010-03-07 23:55:24
【问题描述】:

我这里有这段代码:

NSString *post = [NSString stringWithFormat:@"deviceIdentifier=%@&deviceToken=%@",deviceIdentifier,deviceToken]; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:[NSURL URLWithString:@"http://website.com/RegisterScript.php"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:@"MyApp-V1.0" forHTTPHeaderField:@"User-Agent"];
[request setHTTPBody:postData]; 
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *response = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding]; 

它应该向我的 PHP 服务器发送数据以将设备注册到我们的数据库中,但对于我的一些用户来说,没有发送 POST 数据。有人告诉我这一行:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

可能是导致问题的原因。关于为什么这个脚本有时不会发送 POST 数据的任何想法?在服务器上,我得到了发送失败的数据包跟踪,并且 Content-lenght 出现为 0,因此根本没有发送任何数据。

【问题讨论】:

标签: php ios iphone cocoa-touch http-post


【解决方案1】:

我正在做类似的功能,唯一不同的是您认为错误的行。尝试做

NSMutableData *postData = [NSMutableData data];
[postData appendData:[[NSString stringWithFormat::@"deviceIdentifier=%@&deviceToken=%@",deviceIdentifier,deviceToken]dataUsingEncoding:NSUTF8StringEncoding]];

stringByUrlEncoding 基本上用字符编码的安全字符串替换任何保留字符(我认为这是解释它的最好方法,我的脑子里一片空白)。

希望有帮助

【讨论】:

  • 你在哪里使用 stringByURLEncoding?不过,我确实用你上面的代码替换了我的代码,看起来它正在工作! :D
  • 我在变量上使用它,对不起,我以为我把它放进去了。所以你的将是 [deviceIdentifier stringByUrlEncoding],[deviceToken stringByUrlEncoding]。 drobnik.com/touch/2009/08/url-encoding 解释了为什么使用它以及代码
【解决方案2】:

测试您的数据: NSLog([[NSString alloc] initWithData: postData encoding:NSAsciiStringEncoding]);

【讨论】:

    【解决方案3】:

    顺便说一句,您可以从属性中获取应用版本:

    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey]; [request setValue:[NSString stringWithFormat:@"My App %@", appVersion] forHTTPHeaderField:@"User-Agent"];
    

    【讨论】:

      猜你喜欢
      • 2012-01-19
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多