将HTTP请求标头转换为CURL请求


Convert HTTP Request headers into CURL Request

我有下面给出的HTTP请求头,是否可以将它们转换为curl请求。我怎样才能做到这一点?

POST http://something.org.in/cool HTTP/1.1
Host: something.org.in
Proxy-Connection: keep-alive
Content-Length: 13
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://something.org.in
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://something.org.in/nice
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: connect.sid=s%3AKFD08Azc-yU5nP3VRsPJXerwM4dj4yec.N6Ko3n9vWY15ghJzxZz7FyvZme9ERWANEFc%2Brz0mthU

我不完全确定我是否正确理解了这个问题,但由于它被标记为PHP问题,我认为你想用curl在PHP中执行相同或类似的请求。

在PHP中,可以使用函数curl_setopt()和参数CURLOPT_HTTPHEADER来指定HTTP请求的标头。在这种情况下,函数的第三个参数必须是包含(=all)标头的数组。

基本代码如下:

<?php
// initialize curl handle
$ch = curl_init();
// set request URL
curl_setopt($ch, CURLOPT_URL, 'http://something.org.in/cool');
// We don't want to get the headers in the response, but just the content.
curl_setopt($ch, CURLOPT_HEADER, 0);
// It's a POST method request.
curl_setopt($ch, CURLOPT_POST, 1);
// set cookie
curl_setopt($ch, CURLOPT_COOKIE, 'connect.sid=s0X0P+0KFD08Azc-yU5nP3');
// Now set the HTTP request headers.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Upgrade-Insecure-Requests: 1',
    'Content-Type: application/x-www-form-urlencoded',
    'Accept-Encoding: gzip, deflate',
    'Accept-Language: en-US,en;q=0.8'
    // ... and add more, if needed
));
// execute the request
curl_exec($ch);
?>

为了保持简单,省略了任何错误处理。

可以从命令行创建一个类似的curl请求,如下所示:(为了缩短示例,我省略了一些标题。)

curl -X POST -H 'Accept: text/html,application/xhtml+xml,application/xml' '
   -H 'Upgrade-Insecure-Requests: 1' '
   -H 'Accept-Language: en-US,en;q=0.8' '
   --cookie "connect.sid=s0X0P+0KFD08Azc-yU5nP3"
   -i 'http://something.org.in/cool'

使用-X POST,您可以为请求强制执行POST方法,使用-H 'Header: value',您可以添加标头及其值。如果需要多个标头,则可以重复多次。--cookie选项显然设置了cookie。设置多个cookie需要用;分隔,例如在--cookie "first=value;second=another"中。