问题描述
我有Objective C代码创建一个NSUrlConnection,如下所示:
I have Objective C code creating an NSUrlConnection as follows:
//prepar request
NSString *urlString = [NSString stringWithFormat:@"http://ctruman.info/post.php"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
//set headers
NSString *contentType = [NSString stringWithFormat:@"text/xml"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//create the body
NSString *formData = [[NSString alloc] initWithFormat:@"%@ %@", username.text, password.text];
NSData *postData = [[NSString stringWithString:formData] dataUsingEncoding:NSUTF8StringEncoding];
//post
[request setHTTPBody:postData];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(@"Response: %@", result);
}
然后我有一个PHP脚本应该读取我的POST变量被发送:
Then I have a php script that is supposed to read my POST variables that are being sent:
<?php
print('<pre>');
print_r($_POST);
print('</pre>');
?>
当我执行此操作时,NSLog会吐出以下内容:
When I execute this, NSLog spits out the following:
Array
(
)
为什么不打印我的帖子变量?我是否错误地发出了POST请求?
Why is it not printing out my post variables? Am I making the POST request incorrectly?
推荐答案
正如我所看到的,PHP正在尝试读取您的POST提交,就好像它一样是一个格式正确的PHP POST负载。相反,您将内容类型设置为XML内容 - 这可能会混淆PHP的内容。它正在寻找编码变量,并寻找XML。
As it looks to me, PHP is trying to read your POST submission as if it were a properly formatted PHP POST payload. Instead, you're setting the content-type to XML content -- which probably confuses the heck out of PHP. It's looking for encoded variables, and finding XML.
你有两个选择:
-
读入XML并使用PHP自行解析:
$ xml = file_get_contents('php:// input');
阅读输入的示例如下:
然后您可以使用PHP的xml支持解析它:
重新编码您的目标 - C只是将正常的POST参数发送到服务器。我使用ASIHTTPRequest库,这很容易。
Recode your objective-C to just send normal POST parameters up to the server. I use the ASIHTTPRequest libraries and it's easy. http://allseeing-i.com/ASIHTTPRequest/
这篇关于如何通过PHP中的iPhone应用程序响应POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!