Raspberry Piからの語りかけ、リクエストボディの違い
Raspberry PiからRestletサーバーに話かけるんだけれど、どうもcurlとは違う会話をするようで、調べてみた。
会話の違いを調べるため、Restletサーバー上で以下のコードを書いてみた。
@Post
public String represent(Representation entity) {
String str = getReference().getPath();
System.out.println( str );
String pline = getRequest().getEntityAsText();
System.out.println("request body:"+pline);
このRestサーバーにcurlとpythonからリクエスト投げてみた
curl
>curl -X POST http://192.168.1.62:8010/command/datain/temp -d {"temp":123, "humi":345}
Restサーバーのアウトプット
/command/datain/temp
request body:'{temp:123,humi:354}'
2020-10-04 12:04:03 192.168.1.12 - - 8010 POST /command/datain/temp - 200 18 21 1 http://192.168.1.62:8010 curl/7.65.2 -
Python
s = str(inputValue) #温度センサーから読み取った値
response = requests.post('http://192.168.1.62:8010/command/datain/temp', {'temp':s})
Restサーバーのアウトプット
/command/datain/temp
request body:temp=28.0625
2020-10-04 12:04:38 192.168.1.17 - - 8010 POST /command/datain/temp - 200 18 12 1 http://192.168.1.62:8010 python-requests/2.21.0 -
なんとリクエストボディの中身が違う。
curlはjson形式で送るのに対して、Pythonはデータとして送っているのか?
調べてみるとcurlの-dオプションはjson形式でリクエストボディを送るようだ。
では、Pythonでjson形式でリクエストボディを送ることが出来ればよいことになる(同じデータを送るという意味で)。
で、調べてみるとデータ形式をjsonに変換して送る方法がある。早速試してみる。
payload = {'temp': s }
response=requests.post("http://192.168.1.62:8010/command/datain/temp", json.dumps(payload), headers={'Content-Type':'application/json'})
実行してみた結果は期待通り。
/command/datain/temp
keyword:temp
request body:{"temp": "28.1875"}
2020-10-04 12:47:14 192.168.1.17 - - 8010 POST /command/datain/temp - 200 19 19 3 http://192.168.1.62:8010 python-requests/2.21.0 -
明示的にjson.dumpsを使ってJSON化しないとdataとして送られてしまうようだ。
めでたし、めでたし。と思ったけれど、どうもおかしい。
Pythonと同じデータをcurlで渡すと以下になる。
curl -X POST http://192.168.1.62:8010/command/datain/temp -d {"temp":"34.567"}
/command/datain/temp
keyword:temp
request body:{temp:34.567}
temp=567}
2020-10-04 15:31:18 192.168.1.12 - - 8010 POST /command/datain/temp - 200 13 13 0 http://192.168.1.62:8010 curl/7.65.2 -
ダブルクォーテーションが付かないのだ。つまりKeyもValueも文字列扱いがされていない。
これはどうしたら良いのだろう???
いろいろ調べてみると、-dオプションでRESTリクエストでjson形式データを送る場合は、以下のように設定しないと”が文字化けするとある。
-d {\"temp\":\"34.567\"}
つまり、\(逆スラッシュ)を付けてエスケープ(文字列化)してやる必要があるそうな。
この方法でcurlを投げたら以下となった。
request body: {"temp":"34.567"}
とりあえずcurlで-dオプション付き(JSON形式リクエストボディ)でRESTリクエストが送れるようになった。つまりPythonと同じリクエストボディを送ることができるようになったわけだ。
« restlet serverを立ち上げる | トップページ | JSON形式のリクエストボディからkeyとvalueを抜き出す »
「ラズパイ日記」カテゴリの記事
- NEO-7M GPSモジュールが中国から届いた(2023.01.15)
- TNCアプリにおけるDemoduatorの動作確認(2023.01.09)
- AFSKでの復調について(2023.01.04)
- APRSでのNRZIについて備忘録(2023.01.02)
- pico_tnc 2200Hz(Space)でPhaseをずらす件の備忘録(2022.12.31)
« restlet serverを立ち上げる | トップページ | JSON形式のリクエストボディからkeyとvalueを抜き出す »
コメント