|
http请求有get,post。
php发送http请求有三种方式[我所知道的有三种,有其他的告诉我]。
- file_get_contents();详情见:http://www.cnblogs.com/simpman/p/3419989.html
- curl发送请求。
- fsocket发送。
下面说使用curl发送。
首先环境需要配置好curl组件。
在windows中让php支持curl比较简单:
在php.ini中将extension=php_curl.dll前面的分号去掉,
有人说需要将php根目录的libeay32.dll和ssleay32.dll需要拷贝到系统目录下去。我实验不拷贝也可以。
在linux中,如果使用源码安装,需要在make 之前,./configure --with-curl=path,
其中,path是你的 libcurl库的位置,比如你安装libcurl库之后,
path可能就是/usr/local/,libcurl可以是静态库,也可以是动态库。
注意libcurl库configure的时候,可以将一些不需要的功能去掉,
比如ssl , ldap等。在php configure的时候,会去检查libcurl中某些功能是否被开启,
进而去相应地调整生成的php
两个使用curl发请求的例子。
// 初始化一个 cURL 对象
$curl = curl_init();
// 设置你需要抓取的URL
curl_setopt($curl, CURLOPT_URL, 'http://www.cnblogs.com');
// 设置header 响应头是否输出
curl_setopt($curl, CURLOPT_HEADER, 1);
// 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
// 1如果成功只将结果返回,不自动输出任何内容。如果失败返回FALSE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
// 运行cURL,请求网页
$data = curl_exec($curl);
// 关闭URL请求
curl_close($curl);
// 显示获得的数据
print_r($data);
再一个post方式的例子:
1 //post方式
2 $phoneNumber ="13912345678";
3 $message = "testMessage";
4 $curlPost = "phone=".urlencode($phoneNumber)."&message=".$message;
5 $ch=curl_init();
6 curl_setopt($ch,CURLOPT_URL,'http://mytest/lab/t.php');
7 curl_setopt($ch,CURLOPT_HEADER,0);
8 curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);
9 //设置是通过post还是get方法
10 curl_setopt($ch,CURLOPT_POST,1);
11 //传递的变量
12 curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost);
13 $data = curl_exec($ch);
14 curl_close($ch);
在这个http://mytest/lab/t.php文件中:
1 if(!empty($_POST)){
2 print_r($_POST);
3 }
就先写这么多。
Fsocket:
1 $gurl = "http://mytest/lab/t.php?uu=gggggg";
2 //print_r(parse_url($gurl));
3 echo "以下是GET方式的响应内容:<br>";
4 sock_get($gurl);
5 function sock_get($url)
6 {
7 $info = parse_url($url);
8 $fp = fsockopen($info["host"], 80, $errno, $errstr, 3);
9 $head = "GET ".$info['path']."?".$info["query"]." HTTP/1.0\r\n";
10 $head .= "Host: ".$info['host']."\r\n";
11 $head .= "\r\n";
12 $write = fputs($fp, $head);
13 while (!feof($fp)){
14 $line = fgets($fp);
15 echo $line."<br>";
16 }
17 }
18
19
20 //fsocket模拟post提交
21 $purl = "http://mytest/lab/t.php";
22 echo "以下是POST方式的响应内容:<br>";
23 sock_post($purl,"uu=rrrrrrrrrrrr&&kk=mmmmmm");
24 function sock_post($url, $query)
25 {
26 $info = parse_url($url);
27 $fp = fsockopen($info["host"], 80, $errno, $errstr, 3);
28 $head = "POST ".$info['path']." HTTP/1.0\r\n";
29 $head .= "Host: ".$info['host']."\r\n";
30 $head .= "Referer: http://".$info['host'].$info['path']."\r\n";
31 $head .= "Content-type: application/x-www-form-urlencoded\r\n";
32 $head .= "Content-Length: ".strlen(trim($query))."\r\n";
33 $head .= "\r\n";
34 $head .= trim($query);
35 $write = fputs($fp, $head);
36 print_r(fgets($fp));
37 while (!feof($fp))
38 {
39 $line = fgets($fp);
40 echo $line."<br>";
41 }
42 }
这里还有一篇curl相关的文章,主要是添加了gzip的参数:
php curl 中的gzip压缩性能测: http://www.cnblogs.com/fengwei/p/3549124.html |
|
|