美文网首页
GuzzleHttp在laravel的使用,乱码解决方法

GuzzleHttp在laravel的使用,乱码解决方法

作者: HaRun | 来源:发表于2018-08-20 00:16 被阅读0次

    安装guzzlehttp/guzzle包

    composer require guzzlehttp/guzzle
    

    在app/Http/Controllers下面的HomeController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7;
    use GuzzleHttp\Exception\RequestException;
    use Illuminate\Http\Request;
    
    class HomeController extends Controller
    {
    
        public function test_guzzle_http_get(){
    
            $client = new Client(); //GuzzleHttp\Client
    
            try {
                $response = $client->request('GET', 'https://www.baidu.com/',[
                    'headers'=> [
                        'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
                        'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                        'Accept-Language' => 'zh-CN,zh;q=0.9,en;q=0.8,sm;q=0.7',
                        'Accept-Encoding' => 'gzip'
                    ],
                    'decode_content' => true,// 解密gzip
                    'connect_timeout' => 10
                ]);
    
                 // print_r($response);
    
                // 转换成页面使用的编码,默认为UTF-8,否则乱码!
                $type = $response->getHeader('content-type');
                $parsed = Psr7\parse_header($type);
                $original_body = (string)$response->getBody();
                $utf8_body = mb_convert_encoding($original_body, 'UTF-8', $parsed[0]['charset'] ?: 'UTF-8');
    
                print_r($utf8_body);
    
    
            } catch (RequestException $e) {
                // 此部分是页面出错时输出,如404
                echo Psr7\str($e->getRequest());
                if ($e->hasResponse()) {
                    echo Psr7\str($e->getResponse());
                }
            }
    
        }
    
    }
    
    

    guzzlehttp乱码,解决方法看这段。

                // 转换成页面使用的编码,默认为UTF-8,否则乱码!
                $type = $response->getHeader('content-type');
                $parsed = Psr7\parse_header($type);
                $original_body = (string)$response->getBody();
                $utf8_body = mb_convert_encoding($original_body, 'UTF-8', $parsed[0]['charset'] ?: 'UTF-8');
    
                print_r($utf8_body);
    

    相关文章

      网友评论

          本文标题:GuzzleHttp在laravel的使用,乱码解决方法

          本文链接:https://www.haomeiwen.com/subject/cpnhiftx.html