【问题标题】:cURL freezes when I change the header当我更改标题时 cURL 冻结
【发布时间】:2012-10-04 20:42:40
【问题描述】:

我制作了一个 PHP 脚本来在网站上发送 HTTP 请求。当我不设置标题时,一切都“正常”。结果是错误的。但是当我更改标题时程序会冻结。这是我的代码:

$cookie_file_path='cookie';

$curl_connection =  curl_init('http://www.website.com/path/to/script');

curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);

curl_setopt($curl_connection, CURLOPT_USERAGENT,"Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");

curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($curl_connection, CURLOPT_COOKIEJAR, $cookie_file_path);

curl_setopt($curl_connection, CURLOPT_COOKIEFILE, $cookie_file_path);

curl_setopt($curl_connection,CURLOPT_HTTPHEADER, array('Accept: application/json, text/javascript, */*; q=0.01','Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3','Accept-Encoding: gzip, deflate','Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7','Content-Type: application/json; charset=utf-8','X-Requested-With: XMLHttpRequest','Content-Length: 179','Pragma: no-cache','Cache-Control: no-cache'));

//I use the same header as the website

$post_data=array();

$post_data['address'] = 'my_address';

$post_data['lastname'] = 'my_lastname';

 (...)

foreach ( $post_data as $key => $value)
    $post_items[] = $key . '=' . $value;


$post_string = implode ('&', $post_items);

curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

$result = curl_exec($curl_connection);

file_put_contents('result.html',$result);

主网页在 AJAX 中向脚本发送 POST 请求,我正在尝试对 PHP 执行相同的操作。当我注释掉这一行时,脚本不会冻结:

curl_setopt($curl_connection,CURLOPT_HTTPHEADER, array('Accept: application/json, text/javascript, */*; q=0.01','Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3','Accept-Encoding: gzip, deflate','Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7','Content-Type: application/json; charset=utf-8','X-Requested-With: XMLHttpRequest','Content-Length: 179','Pragma: no-cache','Cache-Control: no-cache'));

这可能是什么原因。我错过了什么吗?

谢谢

【问题讨论】:

    标签: php ajax post curl libcurl


    【解决方案1】:

    一个可能的原因是您发送的是静态字符串;

    Content-Length: 179
    

    ...作为标题。如果您的内容实际上并没有那么长,则网络服务器可能会在回复您的请求之前等待您永远不会发送的数据。

    【讨论】:

    • 感谢您的回复。那么动态设置这个字符串的最佳方法是什么?删除它时出现错误:“处理请求时出错。”,“StackTrace”:“”,“ExceptionType”:“”}”
    • 我用这篇文章解决了这个问题:stackoverflow.com/questions/4271621/php-curl-post-json。数组必须用 Json 编码: curl_setopt($curl_connection, CURLOPT_POSTFIELDS, json_encode($post_data));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2015-02-21
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多