执行没有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)
答案 0 :(得分: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;
}
将内容类型更改为您想要的内容.. JSON,XML任何内容