有时候,我们需要在服务器端模拟post/get请求,也就是在php程序中去实现模拟,该怎么做呢?或者说,在php程序里,给你一个数组,如何将这个数组post/get到另一个地址呢?当然,实用curl很容易办到,那么,不使用curl库又该怎么办呢?其实,在php程序里已经有相关的函数了,它就是stream_context_create。
伪代码:
$data = array(
‘foo’=>‘bar’,
‘baz’=>‘boom’,
‘site’=>‘www.lai18.com’,
‘name’=>‘lai18’
);
d
a
t
a
=
h
t
t
p
b
u
i
l
d
q
u
e
r
y
(
data = http_build_query(
data=httpbuildquery(data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencode',
'content' => $data,
'timeout' => 60,
)
);
$url = "http://www.lai18.net/";
$context = stream_context_create($options);
$result = file_get_contents($url,false,$context);
var_dump($result);
http://www.lai18.com 的代码为:
$data = $_POST;
echo ‘
’;’;
print_r( $data );
echo ‘
运行结果为:
Array
(
[foo] => bar
[baz] => boom
[site] => www.lai18.com
[name] => lai18
)
一些要点讲解:
1:stream_context_create作用:创建并返回一个文本数据流并应用各种选项,可用于fopen()、file_get_contents、soap等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。
2:stream_context_create还能通过增加timeout选项来解决file_get_contents的超时处理。
$opts = array(
‘http’=>array(
‘method’=>“GET”,
‘timeout’=>60,
)
);
//创建数据流上下文
c
o
n
t
e
x
t
=
s
t
r
e
a
m
c
o
n
t
e
x
t
c
r
e
a
t
e
(
context = stream_context_create(
context=streamcontextcreate(opts);
$html =file_get_contents(‘http://www.lai18.com’, false, $context);
3:工作中解决soap连接超时:
$stream = stream_context_create([“http” => [“timeout” => 3]]);//超时时间
try{
if(!$address){
return false;
}
$address = $this->dealAddress($address);
$soapClientOptions = [
'trace' => true,
'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP,
'cache_wsdl' => 0,
'stream_context' => $stream, //定义连接超时为3秒
];
$client = new \SoapClient($this->brightDairyApiUrl, $soapClientOptions);
$arg0 = ['arg0' => $address];
$responseObject = $client->queryAddress($arg0);
$response = json_decode($responseObject->return,true);
if(!isset($response['success']) || !$response['success'] || !isset($response['blockId']) || !$response['blockId']){
return false;
}
return true;
}catch (\SoapFault $e){
//连接光明超时、连接不上,为了不影响用户下单,直接返回true
return true;
}
原文:https://blog.csdn.net/hello_katty/article/details/46371845