如何使用CURL发送带有标头的HTTP get方法

时间:2010-04-09 11:40:37

标签: php curl

我需要使用以下标头发送GET Request方法。 我从HTTP实时标题中获取以下捕获


***http://172.20.22.26/

GET / HTTP/1.1
Host: 172.20.22.26
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Authorization: Basic bWl0aHVuOm1pdGh1bg==

HTTP/1.x 200 OK
Date: Thu, 01 Jan 2009 00:29:20 GMT
Server: HTTPsrv
Connection: Keep-Alive
Keep-Alive: timeout=30, max=100
Transfer-Encoding: chunked
Content-Type: text/html
----------------------------**------------------------------*

我正在使用以下程序。它不起作用。请让我知道我哪里出错了。

  <?php 

 $credentials = "mithun:mithun";

 $url = "http://172.20.22.26";
 $headers = array(
"GET /HTTP/1.1",
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",            "Accept-Language: en-us,en;q=0.5",
"Accept-Encoding: gzip,deflate",
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Keep-Alive: 300",      
"Connection: keep-alive",
"Authorization: Basic " . base64_encode($credentials));
 $ch = curl_init(); 
 curl_setopt($ch, CURLOPT_URL,$url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);               

$data = curl_exec($ch); 
 if (curl_errno($ch)) { 
  print "Error: " . curl_error($ch);
    }
 else {  
 // Show me the result
 var_dump($data);
 curl_close($ch);
  }?>

2 个答案:

答案 0 :(得分:1)

你不想发送所有这些参数,你需要的只有

Host: 172.20.22.26
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Authorization: Basic bWl0aHVuOm1pdGh1bg==

其他标题来自服务器的回复,您无需设置GET /HTTP/1.1,因为它无论如何都隐含在请求中。

答案 1 :(得分:0)

您需要设置CURLOPT_HEADER =&gt;为TRUE在输出中包含标题。