0

在没有 cURL 的情况下进行 PHP 调用(如在此处找到:http ://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/ ),但响应大约需要 10-15 秒回来。它目前只是出现了一个错误。知道如何让它工作吗?我试过 set_time_limit 无济于事。

代码:

function DoPostRequest($url, $data, $optional_headers = null)
{
    $params = array('http' => array('method' => 'POST', 'content' => $data));
    if($optional_headers != null) {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    try {
        $fp = fopen($url, 'rb', false, $ctx);
        $response = stream_get_contents($fp);
    } catch (Exception $e) {
      echo 'Exception: '.$e->getMessage();
    }
    return $response;
}

和错误:

Notice: fopen(): Content-type not specified assuming application/x-www-form-urlencoded in <php url> on line 81 Warning: fopen(http://localhost:59396/Update.ashx): failed to open stream: HTTP request failed! HTTP/1.1 100 Continue in <php url> on line 81 Warning: stream_get_contents() expects parameter 1 to be resource, boolean given in <php url> on line 82 bool(false)
4

1 回答 1

6

尝试

function DoPostRequest($url, $data, $optional_headers = null) {
    $params = array (
            'http' => array (
                    'method' => 'POST',
                    'content' => $data,
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
                    "Content-Length: " . strlen ( $data ) . "\r\n" 
            ) 
    );
    if ($optional_headers != null) {
        $params ['http'] ['header'] = $optional_headers;
    }
    $ctx = stream_context_create ( $params );
    try {
        $fp = fopen ( $url, 'rb', false, $ctx );
        $response = stream_get_contents ( $fp );
    } catch ( Exception $e ) {
        echo 'Exception: ' . $e->getMessage ();
    }
    return $response;
}

将 Content-Type 更改为您想要的 .. JSON、XML 任何东西

于 2012-04-27T16:59:26.833 回答