0

我有一个使用 NSURLRequest 和 NSURLConnexion 将数据发送到 PHP 脚本的应用程序。我想要的是用 post 方法发送一个像“Hello world”这样的数据,我想在我的应用程序上显示“Hello world from myPHPScript.php!” 但我没有网络服务经验,特别是n PHP。

这是我发送请求的objective-c代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL

                                URLWithString:@"http://localhost:8888/testNSURL/index.php"]

                                cachePolicy:NSURLRequestUseProtocolCachePolicy

                                timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];
    NSString *postString = @"myVariable=Hello world !";
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (theConnection) {

        receiveData = [NSMutableData data]; 

}

这是我的 PHP 代码:

<?php
if(isset($_REQUEST["myVariable"])) {
    echo json_encode("Hello from index.php !");
}
else    echo json_encode('Request failed');
?>

我的问题是:

  • 我的 PHP 代码正确吗?
  • 如何echo json_encode("Hello from index.php !");在我的 obj-c 应用程序中捕获?
4

1 回答 1

0

I personally am using ASIFormDataRequest when posting things to a server. When you get info back from this method you can just do something like this to get the data/string value of all that has been echo'd on the server:

- (void)requestFinished:(ASIHTTPRequest *)aRequest {
    NSData *responseData = [aRequest responseData];
    NSString *responseString = [aRequest responseString];
}

Getting a string from Data information is done like so:

[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]
于 2012-04-10T13:08:05.823 回答