Php模拟http请求
方法一:File_get_contents(只能模拟get请求)
$url = “http://www.baidu.com”;
$content = File_get_contents($url);
方法二:Fsockopen
模拟请求行、请求头、空行、请求内容(post请求)
Get:
可以用parse_url($url)函数获取url信息
打开链接
$f = fsockopen(‘域名/ip’,端口,$errno,$error,连接时长);
模拟请求
$http = “GET /index.htmlHTTP/1.1 \r\n”;
$http .= “Host:localhost\r\n”;
$http .= “\r\n”;
写入资源
Fwirte($f,$http); //or fputs
获取数据(可能需要遍历)
Fgetc()/fgets()/fread()
处理数据
输出 or 写下(txt/db)
Post:(数据长度和转码协议必须要有)
….
//模拟请求
$http = “POST /index.html HTTP/1.1 \r\n”;
$http .= “Host:localhost\r\n”;
$http .= “Connection:keep-alive\r\n”;
$http .= “Content-length:43\r\n”; //长度最好与数据长度一致(要求知道接口返回的数据长度)
$http .= “Content-type:application/x-www-form”;
$http .= “\r\n”
$http .= “u_name=george&password=123”;
...
方法三:curl
$url
$ch = Curl_init($url);
配置(具体可以网上搜索一下curl的配置)
Curl_setopt($ch,XXXXXX)
Curl_setopt($ch,XXXXXX)
…
Curl_setopt($ch,XXXXXX)
$data = curl_exec($ch)
//处理数据
输出 or 写下(txt/db)
//关闭资源
curl_close($ch)
curl_error($ch) //输出错误信息