【发布时间】:2014-04-28 05:00:43
【问题描述】:
我正在尝试将一组字符串从 Objective C 发送到 PHP。我最初使用的是 GET,但我知道 GET 不适合发送大量数据。我的数组将有大约 300 个条目。因此,我正在使用 POST。 After going through this page我想出了以下代码
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 中,我收到如下:
<?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 中接收数据。任何帮助或指针将不胜感激
编辑:我改回使用 GET,因为 POST 对我没有帮助。感谢您提供的任何帮助
【问题讨论】:
-
如果你只看正文,它是形式编码的吗?我认为它需要出现在 $_POST... 否则我认为你必须从原始请求中得到它。
-
你也应该通过 Charles 代理查看请求。
标签: php mysql objective-c arrays json