2

我正在尝试让服务器端 POST 在 PHP 中工作。我正在尝试将交易数据发送到支付网关,但我不断收到以下错误:

消息::fopen(https://secure.ogone.com/ncol/test/orderstandard.asp)打开流失败:HTTP 请求失败!HTTP/1.1 411 长度要求

代码:

$opts = array(
    'http' => array(
        'Content-Type: text/html; charset=utf-8',
        'method' => "POST",
        'header' => "Accept-language: en\r\n" .
        "Cookie: foo=bar\r\n"
     )
);

$context = stream_context_create($opts);

$fp = fopen('https://secure.ogone.com/ncol/test/orderstandard.asp', 'r', false, $context);
fpassthru($fp);
fclose($fp);

尝试了一些在网上找到的解决方案 - 主要是在黑暗中拍摄,所以到目前为止还没有运气!

4

2 回答 2

3

只需添加内容长度。一旦你真正开始发送内容,你就需要计算它的长度。

$data = "";
$opts = array(
    'http' => array(
        'Content-Type: text/html; charset=utf-8',
        'method' => "POST",
        'header' => "Accept-language: en\r\n" .
        "Cookie: foo=bar\r\n" .
        'Content-length: '. strlen($data) . "\r\n",
        'content' => $data
     )
);

$context = stream_context_create($opts);

$fp = fopen('https://secure.ogone.com/ncol/test/orderstandard.asp', 'r', false, $context);
fpassthru($fp);
fclose($fp);
于 2012-12-20T11:32:16.873 回答
1

指定content选项,您的代码应该可以工作。无需指定Content-length,PHP 会为您计算:

$opts = array(
    "http" => array(
        "method" => "POST",
        "header" =>
            "Content-type: application/x-www-form-urlencoded\r\n" .
            "Cookie: foo=bar",
        "content" => http_build_query(array(
            "foo" => "bar",
            "bla" => "baz"
        ))
    )
);

笔记:

  • 在上面的示例中,Content-length: 15即使没有明确指定,服务器也会收到标头。
  • POST 数据的内容类型通常是application/x-www-form-urlencoded.
于 2012-12-20T11:33:30.740 回答