HTTPで通信する(POST)
2011年3月14日:iOS
前回、HTTP通信のGETを使用する方法を学びました。今回はGETではなくPOSTを使用する方法を紹介します。
POSTを使ったプログラム
では、以下のページにPOSTで「name=Taro,work=free」を送るプログラムを作ります。
このphpファイルはnameとworkによって表示が変わるようになっています。ソースは以下のとおり。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>サンプル</title> <link rel="stylesheet" type="text/css" href="css/html5reset.css" /> </head> <body> <form method="post" action="post.php"> 名前: <input type="text" name="name" value="名前を記入" size="20"><br /> 職業: <input type="text" name="work" value="職業を記入" size="20"><br /> <input type="submit" /> </form> <?php $name = $_POST['name']; $work = $_POST['work']; echo '名前は'.$name.'で職業は'.$work.'ですね'; ?> </body> </html>
プロジェクトの作成
Xcodeを起動して「Create a new Xcode Project」を選択します。
iOSのSingle View Applicationを選択します。
プロジェクト名と言語を指定して保存します。ここではSwiftとします。
UIの設計
前回のGETと同じようにユーザーインターフェースはデザインします。
プログラムの作成
ボタンを押した際の動作を以下のようにします。
@IBAction func get(sender: UIButton) { let postString = "name=Taro&work=free" var request = URLRequest(url: URL(string: "https://jprogramer.com/samples/post.php")!) request.httpMethod = "POST" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in if error != nil { //エラーの場合(注意:httpのためATSを無効化しないとエラーになる) print(error) return } //うまくいくとphpMsgにレスポンスが入る let phpMsg = String(data: data!, encoding: .utf8)! print("php output: \(phpMsg)") }) task.resume() }
URLRequestにより、POSTとデータ(postString)を指定しています。postStringには”name=Tara&work=free”が入っています。今回はhttpsではなくhttp通信のため、エラーとなります。このエラーを無視するためには、ATSを無効化する必要があります。info.plistにApp Transport Security Settingsを追加し(+ボタンを押し、マニュアルでApp Transport Security Settingsとうつ)、Allow Arbitrary Loadsを選択し(上下の矢印を押すとあるはず)、ValueをYESにしましょう。これでhttpでもエラーなしで値を取得できます。
実行結果
実行すると以下のように「名前はTaroで職業はfreeですね」が返ってきます。
著者:安井 真人(やすい まさと)
@yasui_masatoさんをフォロー