多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 响应体 An HTTP response typically has a body. > HTTP响应通常有一个主体。 Just like the PSR-7 Request object, the PSR-7 Response object implements the body as an instance of`Psr\Http\Message\StreamInterface`. You can get the HTTP response body`StreamInterface`instance with the PSR-7 Response object’s`getBody()`method. The`getBody()`method is preferable if the outgoing HTTP response length is unknown or too large for available memory. > 与Psr -7请求对象一样,Psr -7响应对象将主体作为`Psr\Http\Message\StreamInterface`的实例实现。您可以使用PSR-7响应对象的`getBody()`方法获得HTTP响应体`StreamInterface`实例。如果传出HTTP响应长度未知或对于可用内存来说太大,则使用`getBody()`方法更好。 ~~~php $body = $response->getBody(); ~~~ Figure 12: Get HTTP response body The resultant`Psr\Http\Message\StreamInterface`instance provides the following methods to read from, iterate, and write to its underlying PHP`resource`. > 由此产生的`Psr\Http\Message\StreamInterface`实例提供了以下方法来读取、迭代和写入它的底层PHP`资源`。 * getSize() * tell() * eof() * isSeekable() * seek() * rewind() * isWritable() * write($string) * isReadable() * read($length) * getContents() * getMetadata($key = null) Most often, you’ll need to write to the PSR-7 Response object. You can write content to the`StreamInterface`instance with its`write()`method like this: > 通常,您需要向PSR-7响应对象写入内容。你可以用它的`write()`方法将内容写入`StreamInterface`实例,如下所示: ~~~php $body = $response->getBody(); $body->write('Hello'); ~~~ Figure 13: Write content to the HTTP response body You can also*replace*the PSR-7 Response object’s body with an entirely new`StreamInterface`instance. This is particularly useful when you want to pipe content from a remote destination (e.g. the filesystem or a remote API) into the HTTP response. You can replace the PSR-7 Response object’s body with its`withBody(StreamInterface $body)`method. Its argument**MUST**be an instance of`Psr\Http\Message\StreamInterface`. > 您还可以用一个全新的`StreamInterface`实例`替换`PSR-7响应对象的主体。当您希望将内容从远程目标(例如文件系统或远程API)导入HTTP响应时,这一点特别有用。您可以用它的`withbody (StreamInterface $body)`方法替换PSR-7响应对象的主体。它的参数**必须是`Psr\Http\Message\StreamInterface`的一个实例。 ~~~php use GuzzleHttp\Psr7\LazyOpenStream; $newStream = new LazyOpenStream('/path/to/file', 'r'); $newResponse = $oldResponse->withBody($newStream); ~~~ Figure 14: Replace the HTTP response body **Reminder** The Response object is immutable. This method returns a*copy*of the Response object that contains the new body. > 提醒 > Response对象是不可变的。此方法返回包含新主体的响应对象的副本。