簡體   English   中英

如何使用 GuzzleHttp 重寫此代碼

[英]How to use Rewrite this code with GuzzleHttp

我想在 Laravel 5.8 中使用 Http 門面,但我注意到這個版本的 Laravel 中不包含 Http 門面,所以我安裝了 GuzzleHttp。

但現在我不知道如何用這個包重寫這段代碼:

public function getAddress(Request $request)
    {
        $response=Http::timeout(15)->withHeaders([
            
            'Api-Key' => 'api-key',
        ])->get('https://api.sitename.org/v4/reverse',[
            "lat"=>$request->input('latitude'),
            "lng"=>$request->input('longitude')
        ]);
        $address=$response->json()['formatted_address'];
       return view('address.index',compact('address'));
    }

那么如何使用 GuzzleHttp 正確重寫此代碼以使用Http

由於 guzzle 遵循 psr-7 (我認為),因此沒有內置方法來解碼響應其他事情或對你來說很明顯我猜

try {
    $client = new \GuzzleHttp\Client();
    $response = $client->get('https://api.sitename.org/v4/reverse', [
        RequestOptions::HEADERS => [
            'Api-Key' => 'api-key',
        ],
        RequestOptions::QUERY   => [
            "lat" => $request->input('latitude'),
            "lng" => $request->input('longitude')
        ],
    ]);

    $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);

    dd($response);
} catch (ClientException $e) {
    // Handle error here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM