PHP file_get_contentsでAPIサーバーにGET,POST,画像アップロード

FalconでAPIサーバーを作ってみました。
Python + Falconで高速APIサーバーを作成する
APIサーバー Falcon post,headerの値の取得方法


PHPからこのAPIサーバーに接続してみます。
file_get_contentsで。


file_get_contentsでget



getリクエストを送信してみます。
APIサーバー側はこんな感じ。


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import falcon
  4. class HelloResource(object):
  5.     
  6.     # getされた時の動作
  7.     def on_get(self, req, res):
  8.         msg = {
  9.             "message": "Welcome to the Falcon"
  10.         }
  11.         res.body = json.dumps(msg)
  12. app = falcon.API()
  13. app.add_route("/", HelloResource())
  14. if __name__ == "__main__":
  15.     from wsgiref import simple_server
  16.     httpd = simple_server.make_server("0.0.0.0", 8000, app)
  17.     httpd.serve_forever()
  18.     




取得するPHP側。


  1. <?php
  2. // file_get_contentsでデータを取得
  3. $url = 'http://192.168.1.102:8000';
  4. $raw_data = file_get_contents($url);
  5. // jsonからstdClassに変換
  6. $data = json_decode($raw_data);
  7. // 結果を表示
  8. echo $data->message . PHP_EOL;




実行結果


# php sample.php
Welcome to the Falcon




ここまでは問題なし。




file_get_contentsでpost



データをpostしてみます。
サーバー側はこんな感じです。


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import falcon
  4. class HelloResource(object):
  5.     
  6.     # postされた時の動作
  7.     def on_post(self, req, res):
  8.         
  9.         # postパラメーターを取得
  10.         body = req.stream.read()
  11.         data = json.loads(body)
  12.         
  13.         # パラメーターの取得
  14.         name = data['name']
  15.         
  16.         msg = {
  17.             "message": "Hello, " + name
  18.         }
  19.         res.body = json.dumps(msg)
  20.         
  21. app = falcon.API()
  22. app.add_route("/", HelloResource())
  23. if __name__ == "__main__":
  24.     from wsgiref import simple_server
  25.     httpd = simple_server.make_server("0.0.0.0", 8000, app)
  26.     httpd.serve_forever()
  27.     




PHP側、file_get_contentsでpostします。


  1. <?php
  2. // file_get_contentsでデータを取得
  3. $url = 'http://192.168.1.102:8000';
  4. // POSTするデータを作成
  5. $context = stream_context_create([
  6.     'http' => [
  7.         'method'=> 'POST',
  8.         'header'=> 'Content-type: application/json; charset=UTF-8',
  9.         'content' => json_encode(['name' => 'symfo'])
  10.     ]
  11. ]);
  12. $raw_data = file_get_contents($url, false, $context);
  13. // jsonからstdClassに変換
  14. $data = json_decode($raw_data);
  15. // 結果を表示
  16. echo $data->message . PHP_EOL;




狙い通りの実行結果です。


# php sample.php
Hello, symfo







file_get_contentsで画像ファイルのpost



リクエストヘッダーにファイル名。
ボディーに画像のバイナリデータを要求するサンプルです。


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import falcon
  4. class HelloResource(object):
  5.     
  6.     # postされた時の動作
  7.     def on_post(self, req, res):
  8.         
  9.         # headerからファイル名を取得
  10.         filename = req.get_header('File-Name')
  11.         
  12.         # bodyから画像ファイルのバイナリ取得
  13.         body = req.stream.read()
  14.         
  15.         # ファイルを保存
  16.         with open(filename, 'wb') as f:
  17.             f.write(body)
  18.         
  19.         res.body = json.dumps({'message':'ok'})
  20.         
  21. app = falcon.API()
  22. app.add_route("/", HelloResource())
  23. if __name__ == "__main__":
  24.     from wsgiref import simple_server
  25.     httpd = simple_server.make_server("0.0.0.0", 8000, app)
  26.     httpd.serve_forever()
  27.     





PHP側、ヘッダーにファイル名、ボディーに画像のバイナリデータを設定して送信します。





想定通り、サーバー側に「sample.jpg」というファイル名で画像ファイルが復元できました。


  1. <?php
  2. // file_get_contentsでデータを取得
  3. $url = 'http://192.168.1.102:8000';
  4. // 送信するデータ
  5. $filename = 'sample.jpg';
  6. $image = file_get_contents('cc2.jpg');
  7. // POSTするデータを作成
  8. $header = [
  9.     "Content-Type: application/json; charset=UTF-8;",
  10.     "Content-Length: ".strlen($image),
  11.     "File-Name: " . $filename
  12. ];
  13. $context = stream_context_create([
  14.     'http' => [
  15.         'method'=> 'POST',
  16.         'header'=> implode("\r\n", $header),
  17.         'content' => $image
  18.     ]
  19. ]);
  20. $raw_data = file_get_contents($url, false, $context);
  21. // jsonからstdClassに変換
  22. $data = json_decode($raw_data);
  23. // 結果を表示
  24. echo $data->message . PHP_EOL;





【参考URL】

file_get_contentsでPOSTデータ送信

PHP の file_get_contents は get どころか post も put も delete も upload もできる




関連記事

コメント

プロフィール

Author:symfo
blog形式だと探しにくいので、まとめサイト作成中です。
https://symfo.web.fc2.com/

PR

検索フォーム

月別アーカイブ