サーバーで CakePHP を実行しています。iPhone アプリで JSON オブジェクトをサーバーに送信してから、サーバーにエコー バックさせようとしています。(今は単純にしておきます。) 通常の URL を使用してサーバーにアクセスし、JSON オブジェクトを含むビューを取得しました。これは、JSON をサーバーに投稿する最初の試みです。しかし、うまくいきません。常に null を返します。
私のiPhoneアプリで
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 ソース コードはここには表示されません。