php远程连接http方式

1、socket 方式

    一般是指定网址、端口号、超时时间。

    再对报头进行修改以及传递参数,包括:header、method、content,

    返回的内容包括header报头。

   python的httplib库,php的fsockopen的实现方式与此相同。

  

$dhost = "wx.upsmate.com";

$dport = 80;

$params = "/cgi-bin/getuserlistpage/?access_token=V_5305328e3e107bd2893666052ea16437";





$fp = fsockopen($dhost, $dport, $errno, $errstr, 5);

    if (!$fp) {

        echo "$errstr ($errno)<br />\n";

    } else {

        $out = "GET $params HTTP/1.1\r\n";

        $out .= "Host: $dhost\r\n";

        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";

        $out .= "Connection: Close\r\n\r\n";



        fwrite($fp, $out);

        $response_data = "";

        while (!feof($fp)) {

           $response_data .= fgets($fp, 128);

        }

       // echo  substr($response_data, strpos($response_data,"\r\n\r\n")+4);

        echo $response_data;



       $fp1 = fopen("tmp1.php","w");

       fwrite($fp1, $response_data);

       fclose($fp1);



        fclose($fp);

    }   

 

  

 

2、文件流方式

       fopen、file_get_contents这两种方式,两者最主要的区别在于:fopen可以一行行读取,而file_get_contents是一次性获取全部内容到一个字符串内。

       两者都可以使用stream_context_create()创建资源流。而资源流的作用是:超时设置、代理服务器、请求方式、头信息设置这四个方面。

     

$opts = array(

  'http'=>array(

        'method'=>"GET",

        'timeout'=>5,

   )

);





$context = stream_context_create($opts);



$url = "http://wx.upsmate.com/cgi-bin/getuserlistpage/?access_token=V_5305328e3e107bd2893666052ea16437";

   





         $context =  file_get_contents($url,false,$context);

         echo $context;

fopen方式:

<?php

$timeout = array(

    'http' => array(

        'timeout' => 5 //设置一个超时时间,单位为秒

    )

);

$ctx = stream_context_create($timeout);

if ($fp = fopen("http://example.com/", "r", false, $ctx)) {

$data = ""; while(!feof($fp)) { $data .= fread($fp,4196); } fclose($fp); } ?>

  

 

 参考网址:http://blog.csdn.net/heiyeshuwu/article/details/7841366

      

你可能感兴趣的:(http)