XCode(iPhone)将一个JSON对象发布到cakePHP服务器?

时间:2012-06-03 17:27:54

标签: xcode cakephp

我的服务器上运行了cakePHP。我正在尝试让我的iPhone应用程序将JSON对象发布到服务器,然后让服务器回显它。 (现在保持简单。)我已经使用普通URL访问了很多服务器并获得了包含JSON对象的视图。这是我第一次尝试将JSON发布到服务器上。但它不起作用。它总是回声无效。

在我的iPhone App中

NSDictionary* myDict = [NSDictionary dictionaryWithObjects:dictObjects forKeys:dictKeys];

NSData* jsonObject = [NSJSONSerialization dataWithJSONObject:myDict options:NSJSONWritingPrettyPrinted error:nil];

NSData *requestData;

// I've tried it both ways with this stringified or not
/*
NSString* jsonString = [[NSString alloc]initWithData:jsonObject encoding:NSUTF8StringEncoding];
requestData = [NSData dataWithBytes:jsonString length:[jsonString length]];
*/
requestData = [NSData dataWithData:jsonObject];

urlString = [NSString stringWithFormat:@"http://www.myServer.com/json_tests/echo_json"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:requestData];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:[NSString stringWithFormat:@"%d",[jsonObject length]] forHTTPHeaderField:@"Content-Length"];
currentConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];

我的CakePHP服务器

这是我的控制器文件

public function echo_json() {
   $rawData = $this->params['form'];
   $decodedData = json_decode($rawData);

   $this->layout = 'json';
   $this->set(compact('rawData', 'decodedData'));
}

我的观点有...... echo $rawData; echo json_encode($decodedData);

但是你知道原始html源代码不会显示在这里。

0 个答案:

没有答案