php - 从 iOS 模拟器向本地主机发送 Post 请求

标签 php ios objective-c post

我整个早上都在想办法解决这个问题。我正在使用 MAMP 从 Objective-C 方法向我的 Mac 上的本地服务器发送 POST 请求。当代码运行时,Objective-C 方法似乎连接成功,但我的 PHP 脚本没有收到任何信息。我根据 this answer 重写了我的发送方法,所以发送应该是正确的。我已经在 SO 上经历了 10-15 个类似的问题,但没有运气。我现在的猜测是 URL 有问题,但我找不到问题所在。如果有人可以帮我解决这个问题,那就太好了。

这是我的代码:

IP地址:10.10.2.143

PHP脚本地址:http://localhost:8888/hello_world.php

Objective-C :

- (void)hasToken:(STPToken *)token
{
    NSLog(@"Received token %@", token.tokenId);

    NSString *post = [NSString stringWithFormat:@"stripeToken=%@", token.tokenId];
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://10.10.2.143:8888/hello_world.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (conn)
    {
        NSLog(@"Connection successful!");
    }
    else
    {
        NSLog(@"Connection failed...");
    }
}

PHP:

<?php
    echo "Hello, World!";
    echo $_POST;
?>

输出:

// NSLog
2014-06-16 12:19:45.428 PayPhone Prototype[6519:60b] Received token tok_104EMf4h7nUnb2nUWKejveb9  
2014-06-16 12:19:45.430 PayPhone Prototype[6519:60b] Connection successful!

// PHP
Hello, World!Array

最佳答案

您似乎错过了对 start 的调用NSURLConnection 中的方法...只需调用

[连接开始];

在重新创建连接对象之后。

还有一件事,您处理成功/失败情况的方式并没有真正意义,因为它只检查连接对象是否已创建(或未创建),而不是连接是否成功:

if (conn)
{
    NSLog(@"Connection successful!");
}
else
{
    NSLog(@"Connection failed...");
}

您应该正确实现您的连接对象委托(delegate)方法: – connectionDidFinishLoading: – connection:didReceiveData: – connection:didFailWithError: (正如您链接到的问题中提到的那样)。

关于php - 从 iOS 模拟器向本地主机发送 Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24238212/

相关文章:

python - 如何使用 python-qrtools/ZBar 获取 QR/条形码的编码样式类型?

php - 为什么它不能只突出显示新数据?

PHP 在数组中存储对象引用

ios - 如何仅启动具有手机号码的联系人的 ABPeoplePickerNavigationController?

ios - Swift - 搜索栏初始加载

ios - 从另一个类调用的类函数

PHP 5.4 - 'closure $this support'

通过 sftp 从远程服务器下载 PHP

ios - iOS 上的 opengl : texture only showed correctly on right upper quarter of the view

ios - 当充满地址簿信息的 UITableView 向下滚动时,应用程序崩溃