发送阵列使用POST从客观C到PHP / GET [英] Send array to PHP from objective C using POST/GET

查看:343
本文介绍了发送阵列使用POST从客观C到PHP / GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从目标C发送的字符串数组到PHP。我是用GET最初,但我知道,GET不适合用于发送大量的数据。我的阵列将有大约300个条目。因此,我使用POST。 <一href=\"http://stackoverflow.com/questions/10290767/converting-nsarray-json-nsdata-php-server-json-re$p$psentation?lq=1\">After通过这个页面去我想出了以下code

I am trying to send an array of strings from Objective C to PHP. I was using GET initially but I got to know that GET is not suitable for sending large amount of data. My array would have approximately 300 entries. Therefore, I am using POST. After going through this page I came up with the following code

 NSDictionary *userconnections = [user objectForKey:@"connections"];
             NSMutableArray *connectionsID = [[NSMutableArray alloc] init];
             for (id foo in [userconnections objectForKey:@"values"]) {

                 [connectionsID addObject:[foo objectForKey:@"id"]];
                 //[User sharedUser].connections = connectionsID;

             }

             NSError *error;
             NSData *jsonData = [NSJSONSerialization dataWithJSONObject:connectionsID options:NSJSONWritingPrettyPrinted error:&error];

             NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
             [User sharedUser].connections = jsonData;
             [User sharedUser].connectionsID = jsonString;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost:8888/API.php"]];

    [request setHTTPMethod:@"POST"];

[request setValue:[[User sharedUser]connectionsID] forKey:@"songs"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[[[User sharedUser] connections] length]] forHTTPHeaderField:@"Content-Length"];
 [request setHTTPBody: [[User sharedUser] connections]];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"Return DATA contains: %@", [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil]);

在我的PHP,我收到这样的:

In my PHP, I receive it like:

    <?php 

header("Content-Type: application/json");
$headers = array_change_key_case(getallheaders());


include "dbconnect.php";

$songs = json_decode(stripcslashes($_GET["songs"]));
echo json_encode($songs);

不过,我不能够在PHP接​​收数据。任何帮助或指针将AP preciated

However, I am not able to receive data in php. Any help or pointers would be appreciated

编辑:我转回使用GET,因为POST没有我的帮助。感谢您的帮助,您可以提供

I switched back to using GET since POST was not helping me. Thank you for any help you may offer

推荐答案

几个问题:


  1. 您正在建设一个内容类型应用程序/ JSON 请求,但你的PHP正在尝试读 $ _ POST ['歌曲'] 。你应该做一个或另一个(或发送原始JSON请求,或发送应用程序/ x-WWW的形式urlen codeD 要求)。让我们假设你只是想创建简单的JSON请求(如你的Objective-C code主要是做了)。在这种情况下,你的PHP应该读生JSON像这样:

  1. You are building a Content-Type of application/json request, but your PHP is trying to read the $_POST['songs']. You should do one or the other (either send raw JSON request, or send application/x-www-form-urlencoded request). Let's assume you just wanted to create simple JSON request (as your Objective-C code is largely doing now). In that case, your PHP should read the raw JSON like so:

<?php

// be a good citizen and report that we're going to return JSON response

header("Content-Type: application/json");

// get the lower case rendition of the headers of the request

$headers = array_change_key_case(getallheaders());

// extract the content-type

if (isset($headers["content-type"]))
    $content_type = $headers["content-type"];
else
    $content_type = "";

// if JSON, read and parse it

if ($content_type == "application/json")
{
    // read it

    $handle = fopen("php://input", "rb");
    $raw_post_data = '';
    while (!feof($handle)) {
        $raw_post_data .= fread($handle, 8192);
    }
    fclose($handle);

    // parse it

    $songs = json_decode($raw_post_data, true);
}
else
{
    // report non-JSON request and exit
}

// now use that `$songs` variable here

// if you wanted to report it back to the client for debugging purposes, you should
// recreate JSON response:

$raw_result = json_encode($songs);

// finally, write the body of the response

echo $raw_result;

?>


  • 我会建议删除的的setValue:forKey:与在 @歌曲键您的Objective-C code。假设你只是想发送的原始JSON请求就像我上文所述,那么这是不是需要(,坦率地说,是错误的方式发送应用程序/ x-WWW的形式urlen codeD 要求,反正)。

  • I would suggest removing the the setValue:forKey: with the @"songs" key in your Objective-C code. Assuming you just wanted to send the raw JSON request like I outlined above, then this is not needed (and, frankly, is the wrong way to send a application/x-www-form-urlencoded request, anyway).

    如果您旨在使有效载荷,这样你可以使用 $ _ POST ['歌曲'] ,然后Objective-C的code这样做不使用的setValue:forKey:,而是由人工建筑,中内容类型 应用程序/ x-WWW的形式urlen codeD 和歌曲= ... 将在请求的主体(你不得不使用 CFURLCreateStringByAddingPercentEscapes 为en code中的JSON字符串你会在这个请求通过)。这一切都有点学术,不过,因为我认为你应该使用应用程序/ JSON 要求坚持下去。

    If you intended to make the payload so that you could use $_POST['songs'], then the Objective-C code to do that does not use setValue:forKey:, but consists of manually building a request with a Content-Type of application/x-www-form-urlencoded, and the songs=... would be in the body of the request (and you'd have to use CFURLCreateStringByAddingPercentEscapes to encode the JSON string you'd pass in this request). This is all a bit academic, though, as I think you should stick with the application/json request.

    这篇关于发送阵列使用POST从客观C到PHP / GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆