PHP发送GET、POST请求
发送 GET 请求
1.调用 file_get_contents 函数,以 get 方式获取内容
<?php
$url = "http://username:password@localhost:81/phpGetTest/index.php";
$html = file_get_contents($url);
echo $html;
?>
2.使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展
<?php
$url = "http://username:password@localhost:81/phpGetTest/index.php";
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>
发送 POST 请求
1.使用curl库,发送 xml 数据
<?php
$postUrl = "http://username:password@localhost:81/phpPostTest/index.php";
$xmlData = "
<xml>
<ToUserName>ad775b217</ToUserName>
<FromUserName>tWy3zC3xUgQMR5coXif5SA</FromUserName>
<CreateTime>1366181013</CreateTime>
<MsgType>text</MsgType>
<Content>我的测试</Content>
<MsgId>5867702771251151243</MsgId>
</xml>";
$header[] = "Content-type: text/xml"; //定义content-type为xml
$ch = curl_init ();
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
$response = curl_exec($ch);
if(curl_errno($ch)) {
print curl_error($ch);
}
curl_close($ch);
echo $response;
?>