我正在尋找從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
是否有一個特定的原因,你爲什麼不堅持使用已建立的http方法,如「POST」?它似乎不是發明新東西的最佳實踐。你更新知道什麼編程不好的代理將刪除/更改它。 – KillerX
實際上,通過發佈主體發送json或XML是有意義的。許多標準使用這種方法,例如OAuth和SOAP。雖然多部分也可以工作。 – EJTH
這是一個重複的:[如何從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