ユーザ用ツール

サイト用ツール


サイドバー

Index

はじめてのおつかい






DokuWiki整形記法


PlayGround



development:language:php:postjson

JSONデータのPOST

POSTされたJSONデータ

以下のように、Content-TypeをJSONにして、JSONを本文として送信する。

Content-Type:application/json

{key1=value1,key2=value2}

受信

<?php
  $json_string = file_get_contents('php://input');
 
  $obj = json_decode($json_string);
  var_dump($obj);

php://input は読み込み専用のストリームで、 リクエストの body 部から生のデータを読み込みます

送信

<?php
 
  $context = stream_context_create(
    array(
      'http' => array(
        'method'=> 'POST',
        'header'=> 'Content-type: application/json; charset=UTF-8',
        'content' => json_encode(
          array(
            'key1' => 'Value1',
            'key2' => 'Value2'
          )
        )
      )
    )
  );
 
  file_get_contents('http://post.example.com/api/sample', false, $context);

curlで送信

$ curl -X POST http://post.example.com/api/sample -H 'Content-Type: application/json' -d @json_file_name

$ curl -X POST http://post.example.com/api/sample -H 'Content-Type: application/json' -d '{"postdata":{"key1":"Value1","key2":"Value2"}}'

参考

development/language/php/postjson.txt · 最終更新: 2017/04/14 14:21 (外部編集)