2013-04-12 24 views
0

我正在尋找從iPhone SDK調用HTTP_POST到我的服務器上的PHP文件。如果我把這個如下:服務器objective-c json php

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://*****/api2/index.php"]]; 

[request setHTTPMethod:@"POST"]; 
[request addValue:@"postValues" forHTTPHeaderField:@"METHOD"]; 

//create data that will be sent in the post 
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; 
[dictionary setValue:@2 forKey:@"value1"]; 
[dictionary setValue:@"This was sent from ios to server" forKey:@"value2"]; 

//serialize the dictionary data as json 
NSData *data = [[dictionary copy] JSONValue]; 

[request setHTTPBody:data]; //set the data as the post body 
[request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"]; 

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
if(!connection){ 
    NSLog(@"Connection Failed"); 
} 

PHP代碼

if ($_SERVER['HTTP_METHOD'] == 'postValues'){ 
$body = $_POST; 
$id;// value1 from dictionary 
$name; // value2 from dictionary 
} 

請$ ID幫助和$ name

+0

是否有一個特定的原因,你爲什麼不堅持使用已建立的http方法,如「POST」?它似乎不是發明新東西的最佳實踐。你更新知道什麼編程不好的代理將刪除/更改它。 – KillerX

+0

實際上,通過發佈主體發送json或XML是有意義的。許多標準使用這種方法,例如OAuth和SOAP。雖然多部分也可以工作。 – EJTH

+0

這是一個重複的:[如何從iPhone發佈請求獲取json數據](http://stackoverflow.com/questions/3656983/how-to-get-json-data-from-iphone-post-request)(簡稱答案是,JSON數據駐留在'$ body ['json']')這裏是另一個答案更多的信息: [發送json使用nsurlrequest](http://stackoverflow.com/questions/10645317/ios-5-發送-json-using-nsurlrequest-and-parsing-in-php-via-post) – Rikkles

回答

1

首先,這個請求的方法是POST,不postValues。您所做的只是添加一個標頭,其名稱爲METHOD,值爲postValues,因此,如果您想檢查該標題,則需要查看所使用的服務器與PHP之間的接口。對於Apache,這是apache_request_headers()。然後,如果您將JSON對象設置爲請求的主體,那麼您需要閱讀正文以獲取它。要做到這一點,你需要閱讀php://input。所以,你的例子變成:

$body = json_decode(file_get_contents('php://input'), true); 
$id = $body['value1'];// value1 from dictionary 
$name = $body['value2']; // value2 from dictionary 
0

你既可以查詢發送多餘的值(和檢索使用$ _GET) 或者您可以將值放在您的json數據中。

而且檢索您的JSON作爲對象的正確的方法是:

$bodyAsObject = json_decode(file_get_contents('php://input'));