在不使用curl下,使用fopen、或file_get_contents 模拟post、get请求数据
话不多说,直接上代码:
<?php $data = array( 'test'=>'bar', 'baz'=>'boom', 'site'=>'www.nimip.com', 'name'=>'nimip.com'); $data = http_build_query($data); //$postdata = http_build_query($data); $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $data, 'timeout' => 60 // 超时时间(单位:s) ) ); $url = "http://172.28.81.238:888/rpc/message/test"; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); echo $result;
https://www.php.net/manual/zh/function.stream-context-create.php
stream_context_create
stream_context_create — 创建资源流上下文
options
必须是一个二维关联数组,格式如下:$arr['wrapper']['option'] = $value 。
默认是一个空数组。
params
必须是 $arr['parameter'] = $value 格式的关联数组。 请参考 context parameters 里的标准资源流参数列表。
代码示例:
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);options相关配置项
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
$opts = array('ftp' => array(
'proxy' => 'tcp://vbinprst10:8080',
'request_fulluri'=>true,
'header' => array(
"Proxy-Authorization: Basic $auth"
)
),
'http' => array(
'proxy' => 'tcp://vbinprst10:8080',
'request_fulluri'=>true,
'header' => array(
"Proxy-Authorization: Basic $auth"
)
)
);不但可以模拟post、get提交,还可以使用ftp相关协议。
stream_context_create() 作用:创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。