0からOAuthのクライアントコードを書くのは面倒なので、oauthconsumerを使用する。
実はライブラリのページには以下のような質問が掲載されているが返答がされていないようだ。
Hello, I am trying to submit some JSON data to a web service using a POST request. For some reason however, the framework seems to look for additional parameters in the HTTP body where I put my JSON data. This results in an index-out-of-range exception since it is unable to split the HTTP body into parameter components.
以下のように実装すると、application/jsonでPOSTすることができる。
NSURL *url = [NSURL URLWithString:@"https://example.com/user/1/flights/"]; OAConsumer *consumer = [[OAConsumer alloc] initWithKey:@"mykey" secret:@"mysecret"]; OAToken *accessToken = [[OAToken alloc] initWithKeychainUsingAppName:@"MyApp" serviceProviderName:@"Example.com"]; OAMutableURLRequest *req = [[OAMutableURLRequest alloc] initWithURL:url consumer:consumer token:accessToken realm:nil signatureProvider:nil]; [req setHTTPMethod:@"POST"]; [req prepare]; [req setHTTPBody:[(NSString*)jsonStr dataUsingEncoding:NSUTF8StringEncoding]]; [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; OADataFetcher *fetcher = [[OADataFetcher alloc] init]; [fetcher fetchDataWithRequest:request delegate:self didFinishSelector:@selector(apiTicket:didFinishWithData:) didFailSelector:@selector(apiTicket:didFailWithError:)];
ちなみに通常のPOSTをしたい場合は、ドキュメントにもあるように以下のようにする。
NSURL *url = [NSURL URLWithString:@"https://example.com/user/1/flights/"]; OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url consumer:consumer token:accessToken realm:nil signatureProvider:[[OAPlaintextSignatureProvider alloc] init]]; OARequestParameter *nameParam = [[OARequestParameter alloc] initWithName:@"title" value:@"My Page"]; OARequestParameter *descParam = [[OARequestParameter alloc] initWithName:@"description" value:@"My Page Holds Text"]; NSArray *params = [NSArray arrayWithObjects:nameParam, descParam, nil]; [request setParameters:params]; OADataFetcher *fetcher = [[OADataFetcher alloc] init]; [fetcher fetchDataWithRequest:request delegate:self didFinishSelector:@selector(apiTicket:didFinishWithData:) didFailSelector:@selector(apiTicket:didFailWithError:)];
PHP
ちなみにPHPで同じことをする場合は以下のように記述する。
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://justoneplanet.info'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, '{"hogehoge" : "fugafuga"}'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_HEADER, TRUE); $result = curl_exec($ch);