HTTPプロトコルを使用して、json形式のデータをサーバに転送するpythonコードを作成しました。使用したpythonはバージョン2.7.9で作成したプログラムはRaspberry PI 3で実行させました。
pythonソースコード
次のようにして、json形式のrequestメッセージを送信します。「jsondump.php」は、サーバから受け取ったhttpメッセージのヘッダとbodyをレスポンスとして返すphpプログラムです。
test.py
import json
import requests
def main():
dict = {
"foo": "0987654321"
}
response = requests.post(
'http://127.0.0.1/jsondump.php',
json.dumps(dict),
headers={'Content-Type': 'application/json'})
print response.text
if __name__=='__main__':
main()
jsondump.php
<?php
try {
print_r(getallheaders() );
echo "body".file_get_contents('php://input');
} catch (PDOException $e){
var_dump($e->getMessage());
}
?>
Httpプロトコルを使用したjsonによるデータ送信
作成したプログラムを実行すると、次のように端末に表示されます。
$ python test.py
Array
(
[Host] => 133.242.236.247
[Content-Length] => 21
[Accept-Encoding] => gzip, deflate
[Accept] => */*
[User-Agent] => python-requests/2.4.3 CPython/2.7.9 Linux/4.1.19-v7+
[Connection] => keep-alive
[Content-Type] => application/json
)
body{"foo": "0987654321"}