zoukankan      html  css  js  c++  java
  • stream_context_create()模拟POST/GET

    有时候,我们需要在服务器端模拟 POST/GET 等请求,也就是在 PHP 程序中去实现模拟,该怎么做到呢?或者说,在 PHP 程序里,给你一个数组,如何将这个数组 POST/GET 到另外一个地址呢?当然,使用 CURL 很容易办到,那么如果不使用 CURL 库,又该怎么办呢?其实,在 PHP 里已经有相关的函数实现了,这个函数就是接下来要讲的 stream_context_create()。具体看下面代码:

    stream.php

    <?php
    $data = array(
        'foo'=>'bar', 
        'baz'=>'boom', 
        'site'=>'www.nowamagic.net', 
        'name'=>'nowa magic'); 
        
    $postData = http_build_query($data); 
    
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postData
        )
    );
    
    $url = "http://127.0.0.1/test.php";
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    
    echo $result;//输出返回值

    test.php

    <?php
    $data = $_POST;
    echo '<pre>';
    print_r( $data );
    echo '</pre>';

    结果:

    Array
    (
        [foo] => bar
        [baz] => boom
        [site] => www.nowamagic.net
        [name] => nowa magic
    )

    另外,stream_context_create 还能通过增加 timeout 选项解决file_get_contents超时处理:
    代码如下:
    $opts = array(
      'http' => array(
            'method'=>"GET",
            'timeout'=>60,
      )
    );
    //创建数据流上下文
    $context = stream_context_create($opts);
    
    $html = file_get_contents('http://127.0.0.1/test.php', false, $context);
  • 相关阅读:
    设计模式之策略设计模式
    我的Java编码规范
    Jvm中的垃圾回收
    Jvm运行时内存解析
    SSH框架的搭建
    xshell5运行hadoop集群
    安装虚拟机和网络配置
    大数据技术原理与运用知识
    Redis高级应用解析:缓存穿透、击穿、雪崩
    B+Tree原理及mysql的索引分析
  • 原文地址:https://www.cnblogs.com/gide/p/4599365.html
Copyright © 2011-2022 走看看