如何使用guzzlehttp使用此代码重写

发布于 2025-02-07 22:05:39 字数 641 浏览 3 评论 0原文

我想在Laravel 5.8中使用HTTP立面,但我注意到此版本的Laravel不包括HTTP立面,因此我安装了GuzlehTTP。

但是现在我不知道如何使用此软件包重写此代码:

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

I wanted to use Http facade in Laravel 5.8 but I noticed that Http facade is not included in this version of Laravel so I installed GuzzleHttp.

But now I don't know how to rewrite this code with this package:

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'));
    }

So how can I properly rewrite this code using GuzzleHttp in order to use the Http ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疯狂的代价 2025-02-14 22:05:39

由于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
}

Since guzzle follows psr-7 (I think) there is no builtin method to decode response other things or obvious to you I guess

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文