php 模拟http请求

15 篇文章 0 订阅

原文
GuzzleHttp

GuzzleHttp模拟表单提交 并用nodejs接受数据
php代码

use GuzzleHttp\Client;	
$array = array(
            'token'=>$token
        );
        $data = json_encode($array);
        $client = new Client();
        $response = $client->request('POST', $url, [
            'form_params' => [
                'token' => $token,
                'other_field' => '123',
                'nested_field' => [
                    'nested' => 'hello'
                ]
            ]
        ]);
        // return redirect("http://localhost:3000")->with('token',$token);
        return $response;

js接收数据

const bodyParser = require('body-parser');
server.listen(80);
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

app.post('/', async (req, res) => {
    let body =req.body;
    let token = req.body.token;
    res.sendFile(__dirname + '/views/index.html');
});

PHP 发送 HTTP 请求的方式
那么这里整理一下除了使用 cURL 外 PHP 发送 HTTP 请求的方式。

1.cURL
略过

2.stream 流的方式
stream_context_create 作用:创建并返回一个文本数据流并应用各种选项,可用于 fopen (), file_get_contents () 等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。

以一个 POST 请求为例:

<?php
/**
 * Created by PhpStorm.
 * User: tanteng
 * Date: 2017/7/22
 * Time: 13:48
 */
function post($url, $data)
{
    $postdata = http_build_query(
        $data
    );

    $opts = array('http' =>
                      array(
                          'method' => 'POST',
                          'header' => 'Content-type: application/x-www-form-urlencoded',
                          'content' => $postdata
                      )
    );
    $context = stream_context_create($opts);
    $result = file_get_contents($url, false, $context);
    return $result;
}

关于 PHP stream 的介绍文章:https://www.oschina.net/translate/understa…

3.socket 方式
使用套接字建立连接,拼接 HTTP 报文发送数据进行 HTTP 请求。

一个 GET 方式的例子:

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值