用php实现stream模式
首先是前端的代码是:
var url = "https://www.example.com"; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestData), }).then(response => { const reader = response.body.getReader(); return new ReadableStream({ start(controller2) { function push() { reader.read().then(({ value, done }) => { if (done) { controller2.close(); return; } controller2.enqueue(value); push(); }) } push(); } }); }).then(str const reader = stream.getReader(); reader.read().then(function processResult(result) { if (result.done) { console.log("finish"); return; } const chunk = decoder.decode(result.value, { stream: true }); console.log(chunk); return reader.read().then(processResult); }); }).catch(error => console.error(`Error fetching stream:
PHP端代码是:
public function stream_gpt() { if (ob_get_level() > 0) { ob_end_clean(); } header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); header('Connection: keep-alive'); header('X-Accel-Buffering: no'); echo "XXXX"; flush(); die(); }
PHP通过stream调用远端服务
$post_params = input(); $opts = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/json', 'content' => json_encode($post_params) ), ); $context = stream_context_create($opts); $remoteUrl = 'https://www.example.com'; $handle = fopen($remoteUrl, 'r', false, $context); while (!feof($handle)) { echo fgets($handle,4); flush(); } fclose($handle);
如果出现错误“422 unprocessable entity”,应该是post json的参数格式不对造成的,请调整http post的content参数,应该是string(json)格式