控制器 app/Controller/IndexController.php

<?php
namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
use Hyperf\HttpMessage\Cookie\Cookie;

/**
 * @AutoController();
 */
class IndexController
{
    /**
     * 返回json格式示例
     */
    public function json(ResponseInterface $response):Psr7ResponseInterface
    {
        $data = [
            'name'=>'huyongjian',
            'qq'=>'308830232@qq.com'
        ];
        return $response->json($data);
    }

    /**
     * 返回xml格式示例
     */
    public function xml(ResponseInterface $response):Psr7ResponseInterface
    {
        $data = [
            'name'=>'huyongjian',
            'qq'=>'308830232@qq.com'
        ];
        return $response->xml($data);
    }

    /**
     * 返回raw格式示例
     */
    public function raw(ResponseInterface $response):Psr7ResponseInterface
    {
        $data =[
            'name'=>'huyongjian',
            'qq'=>'308830232@qq.com'
        ];
        $data = json_encode($data);
        return $response->raw($data);
    }

    /**
     * redirect示例
     *
     */
    public function redirect(ResponseInterface $response):Psr7ResponseInterface
    {
        return $response->redirect('/index/json');
    }

    /**
     *cookie设置示例
     */
    public function cookie(ResponseInterface $response):Psr7ResponseInterface
    {
        $cookie = new Cookie('name','huyongjian');
        return $response->withCookie($cookie)->withContent('Hello Hyperf cookie is ok');
    }

    /**
     * 文件下载示例
     */
    public function download(ResponseInterface $response):Psr7ResponseInterface
    {
        return $response->download(BASE_PATH . '/public/download.txt', 'download.txt');
    }
}

添加download.txt public/download.txt

download test

浏览器访问测试

json

http://118.195.173.53:9501/index/json

结果

{"name":"huyongjian","qq":"308830232@qq.com"}

xml

http://118.195.173.53:9501/index/xml

结果

<root>
<name>huyongjian</name>
<qq>308830232@qq.com</qq>
</root>

raw

http://118.195.173.53:9501/index/raw

结果

{"name":"huyongjian","qq":"308830232@qq.com"}

redirect

http://118.195.173.53:9501/index/redirect

结果

{"name":"huyongjian","qq":"308830232@qq.com"}

cookie

http://118.195.173.53:9501/index/cookie

结果

Hello Hyperf cookie is ok

Application>Cookies 可以看到设置的cookie值

文件下载

http://118.195.173.53:9501/index/download