简体   繁体   English

Laravel-将请求重定向到外部URL并返回其响应作为响应

[英]Laravel - redirect request to external url and return its response as response

i'm building an app using Laravel for providing some API for an android application, and i'm using some external APIs from another server (with another URL). 我正在使用Laravel构建一个应用程序,以便为Android应用程序提供一些API,并且我正在使用来自另一台服务器(具有另一个URL)的一些外部API。 i want to make something like proxy or tunnel for external API requests from android side but in my own URL. 我想为来自Android端的外部API请求制作类似代理或隧道的内容,但使用我自己的URL。

for example: android wants to request for externalUrl.com/api/objects but i want he request to this myDOmain.com/api/x/objects and get the exact same response that the first link returns, without any change. 例如:android要请求externalUrl.com/api/objects,但我希望他向myDOmain.com/api/x/objects请求并获得与第一个链接完全相同的响应,而没有任何更改。 and there is more than one external API, and i don't want to write separate code for each one. 而且有一个以上的外部API,我不想为每个API编写单独的代码。

need something like this : 需要这样的东西:

Route::any('/x/{somewhere}', function($request){
return [$request, externalUrl.com/api/{somewhere}]->response;
})

i'm not asking for http request libraries! 我不要求http请求库! i want to redirect request to another domain and return its request. 我想将请求重定向到另一个域并返回其请求。

You can use Guzzle : 您可以使用Guzzle:

use Guzzle\Http\Client;
use Guzzle\Stream\PhpStreamRequestFactory;
[...]
$request = new Client("externalUrl.com/api/{$somewhere}");

$response = $request->send();
return $response->getBody();

Best option is to install Guzzle. 最好的选择是安装Guzzle。 https://github.com/guzzle/guzzle https://github.com/guzzle/guzzle

It's really simple to use it. 使用起来真的很简单。

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'externalUrl.com/api/{somewhere}');

return $response->getBody();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM