使用curl发送请求时出现无效的头错误

4
这里是我的代码。
echo 22;
$url = 'http://www.10bet.com/pagemethods.aspx/GetLeaguesContent';

$fields = array(    
        'BranchID' => urlencode('1') , 
        'LeaguesCollection' => urlencode('10098') , 
                );

$fields_string  = '';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');



$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type : application/json; charset=utf-8'));
$result = curl_exec($ch);
curl_close($ch);
var_dump( $result );

我不断收到以下错误信息:
Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.
2个回答

7

您出现了意外的错误


Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

由于您使用了无效的标题名称 :)
您使用了:
Content-Type : application/json; charset=utf-8

注意标题名称中空格的存在。
正确的使用方法应该是:
Content-Type: application/json; charset=utf-8

1

如果有人像@ZombieSpy描述的那样遇到了这个问题,并想知道这种严格性是从哪里来的,那么答案就在https://datatracker.ietf.org/doc/html/rfc7230#section-3.2中定义,如下所示:

3.2.  Header Fields

   Each header field consists of a case-insensitive field name followed
   by a colon (":"), optional leading whitespace, the field value, and
   optional trailing whitespace.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接