我整个上午都在想这个问题。我从Objective-C方法发送POST请求到我的Mac上的本地服务器,使用MAMP。当代码运行时,Objective-C方法似乎连接成功,但我的PHP脚本没有接收到任何内容。我根据这个答案重写了我的send方法,所以发送应该是正确的。我已经回答了10-15个类似的问题,但没有运气。我现在的猜测是URL有问题,但我找不到问题。如果有人能帮我解决这个问题,就太好了。
下面是我的代码:
IP: 10.10.2.143
脚本地址: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
似乎您错过了对NSURLConnection
中start
方法的调用…只需调用
[conn start];
在重新创建连接对象后立即执行。
还有一件事,您处理成功/失败情况的方式实际上没有意义,因为它只检查连接对象是否创建(或未创建),而不是连接是否成功:if (conn)
{
NSLog(@"Connection successful!");
}
else
{
NSLog(@"Connection failed...");
}
你应该正确地实现你的连接对象委托方法:– connectionDidFinishLoading:
– connection:didReceiveData:
– connection:didFailWithError:
(正如你所链接到的问题中提到的)