【问题标题】:How to send Accept Encoding header with curl in PHP如何在 PHP 中使用 curl 发送 Accept Encoding 标头
【发布时间】:2016-05-12 16:33:22
【问题描述】:

如何在 PHP 中使用 curl 发送 Accept Encoding 标头

  $data=json_encode($data);
$url = 'url to send';
$headers = array(
        'Content-Type: application/json'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);        
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSLVERSION, 4);
    $datas  = curl_exec($ch);
    curl_close($ch);

如何解压响应

【问题讨论】:

  • Content-Type 标头从服务器发送到客户端。您正在寻找 Accept* 标头。 (例如AcceptAccept-EncodingAcccept-Language)。这告诉服务器你的用户代理支持什么。
  • @Mike 不完全一样,客户端也可以发送Accept-Encoding 标头请求。
  • @PedroLobito 有趣。这与Accept 有何不同?
  • @PedroLobito 抱歉,我在这里误读了您的第一条评论。我以为你是说客户可以发送Content-Type。从上面的链接,The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient,所以我是对的;它只能从服务器发送到客户端。

标签: php curl gzip


【解决方案1】:

你可以使用CURLOPT_ENCODING:

curl_setopt($ch, CURLOPT_ENCODING, "");

“Accept-Encoding:”标头的内容。这使解码 的回应。支持的编码是“identity”、“deflate”和 “压缩包”。如果设置了一个空字符串“”,则一个包含所有 发送支持的编码类型。

http://php.net/manual/en/function.curl-setopt.php


或者,您可以发送标头:

$headers = array(
        'Accept: text/plain'
    );

强制回复text/plain

【讨论】:

  • 接受:text/plain 不会强制执行任何操作。结果仍然是 HTML。
【解决方案2】:

如果您的意思是如何解压缩响应,我是这样做的:

<?php
....
$headers = array(
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Encoding: gzip, deflate",
    "Accept-Charset: utf-8;q=0.7,*;q=0.3",
    "Accept-Language:en-US;q=0.6,en;q=0.4",
    "Connection: keep-alive",
);
....
$response = curl_exec($curl);
// check for curl errors
if ( strlen($response) && (curl_errno($curl)==CURLE_OK) && (curl_getinfo($curl, CURLINFO_HTTP_CODE)==200) ) {
    // check for gzipped content
    if ( (ord($response[0])==0x1f) && (ord($response[1])==0x8b) ) {
        // skip header and ungzip the data
        $response = gzinflate(substr($response,10));
    }
}
// now $response has plain text (html / json / or something else)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2011-04-08
    • 2013-08-13
    • 2012-06-18
    • 2015-04-20
    • 1970-01-01
    相关资源
    最近更新 更多