Skip to content

Instantly share code, notes, and snippets.

@Kesin11
Created August 30, 2012 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kesin11/3523719 to your computer and use it in GitHub Desktop.
Save Kesin11/3523719 to your computer and use it in GitHub Desktop.
HTTPのPOST通信がうまくいかない
//phpのサーバーに対してObjective-CからHTTPのPOSTでJSONを送ろうとしているのですがうまくいかないです。
//何か知ってる人がいたら教えてもらえると助かります
+ (NSData *)httpPostExpectReturn:(NSData *)json :(NSString *)urlString{
//HTTP POST
NSString* encodedUrl = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"http POST url: %@",encodedUrl);
//うまくいかないけど本当はこういうJSONを送りたい
NSArray *requestDict = @[@{@"key":@"value"},@{@"key":@"value2"}];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:requestDict options:NSJSONWritingPrettyPrinted error:&error];
//こういう形で送ればうまくいく
NSString *post = [NSString stringWithFormat:@"example=test&p=1&test=yourPostMessage&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(@"Reply: %@", theReply);
}
//サーバー側は受け取ったJSONをそのまま送り返す仕組みになってる
//サーバーのログを見るとPOST自体は受信しているようです
//うまくいく場合:
2012-08-30 16:18:18.892 HelloMap[15368:15803] Reply:
array(4) {
["example"]=>
string(4) "test"
["p"]=>
string(1) "1"
["test"]=>
string(15) "yourPostMessage"
["this"]=>
string(9) "isNotReal"
}
//うまくいかない場合:
2012-08-30 16:22:04.307 HelloMap[15400:15803] Reply:
array(0) {
}
@Kesin11
Copy link
Author

Kesin11 commented Aug 30, 2012

この問題は解決しました!
問題はPHP側で($_POST)で値を取得すると
key=value
は解釈できるが、
{"key":"value"}
は解釈できないということのようでした。
PHP側でphp://inputを使って値を取得してもらうことで無事に解決しました。

参考URL: http://stackoverflow.com/questions/10645317/ios-5-sending-json-using-nsurlrequest-and-parsing-in-php-via-post

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment