0

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

在我的 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 源代码。

4

0 回答 0