通过http流发送post请求

  一般都是用curl扩展来完成,看了手册的通过stream的方式更加简单。

  请求脚本stream.php

 1 $url = 'http://localhost/stream_api.php';
 2 
 3 $body = [
 4     'name'=>'lemon',
 5     'age'=>20,
 6     'sex'=>'gener'
 7 ];
 8 
 9 $opts = [
10     'http'=>[
11         'method'=>'POST', //这里区分大小写
12         'content'=>json_encode($body),
13         'header'=>'Content-type:application/x-www-form-urlencoded'
14     ]
15 ];
16 //创建流上下文
17 $context = stream_context_create($opts);
18 //将上下文传入
19 $res = file_get_contents($url,false,$context);
20 print_r($res);

  接收 stream_api.php 

<?php
header('Content-type:application/json');
$body = @file_get_contents('php://input');
//file_put_contents('2.php',$body);
$data = json_decode($body,true);
$data['name'] = 'jack';

echo json_encode($data);

  最后打印出['name'=>'jack',......]

原文地址:https://www.cnblogs.com/loveyouyou616/p/5550036.html