2013年1月23日水曜日

iPhoneでPOSTメソッドによるデータを取得する方法

iPhoneではGETメソッドでデータをやり取りするのは簡単だけど、 POSTメソッドでやりとりする場合少しめんどくさい。

GETでデータを送信する場合はURLに入れればいいだけでできる。

NSString *s = [NSString stringWithFormat:@"http://localhost:8888/index.php?table_name=products&query_type=select"];    
NSURL  *url = [NSURL URLWithString:s];

POSTメソッドの場合はリクエストをNSMutableURLRequestで宣言する。
その後、POSTメソッドで送る内容をリクエストのHTTPBodyに代入することで可能となる。
    NSURL *url = [[NSURL alloc]initWithString:@"http://localhost:8888/dbconnect/POSTMethodFromiOS.php"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    
    // MethodにPOSTを指定する。
    request.HTTPMethod = @"POST";
    
    NSString *email    = @"momo@momochibi.com";
    NSString *password = @"momo";
    
    NSString *body = [NSString stringWithFormat:@"email=%@&password=%@",email,password];
    
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];

POSTメソッドでサーバにデータを送る場合は、何かしらの処理をした結果を取得したいと思う。
僕はXML形式に処理されたデータを変換し、そのデータを取得するようにしている。

0 件のコメント:

コメントを投稿