【问题标题】:Convert HTTP Request headers into CURL Request将 HTTP 请求标头转换为 CURL 请求
【发布时间】:2015-10-30 07:05:19
【问题描述】:

我有如下给出的 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 http-post forms


【解决方案1】:

我不完全确定我是否正确理解了这个问题,但由于它被标记为 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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2017-06-25
    • 2020-12-21
    • 2018-04-16
    • 2021-02-06
    • 2017-01-13
    相关资源
    最近更新 更多