Laravel:HTTPrequest到另一台服务器

时间:2014-09-03 06:35:11

标签: php http laravel httprequest

如何通过Laravel向另一台服务器发出http请求?

我很乐意提供您需要的任何信息

非常感谢任何帮助

5 个答案:

答案 0 :(得分:3)

取决于请求的复杂程度。你可以使用curl或者甚至是file_get_contents来处理简单的get请求,或者安装像Guzzle这样的包来处理更复杂的事情。

https://github.com/guzzle/guzzle

答案 1 :(得分:1)

正常' PHP,你可以使用Curl来处理http协议(POST / GET)。如果您使用的是Laravel,您可以构建自己的卷曲方法,也可以使用与composer / Laravel兼容的第三方卷曲库:

https://packagist.org/packages/unikent/curl

答案 2 :(得分:1)

如果出于某种原因您正在运行旧的Laravel版本或不想为耗时而烦恼,则可以始终使用php-curl:

sudo apt-get install php-curl

然后根据您的需要创建一个函数,例如POST:

function httpPost($url, $data){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

或GET

public function httpGet($url){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

只需在控制器中调用函数:

$response = $this->httpPost($url, $data); 
$response = $this->httpget($url);

其中$ url是您的端点,您需要在其中发送请求和$ data-必需的参数。

答案 3 :(得分:0)

你可以使用Guzzle 在composer.json文件中添加依赖包

{
    "require": {
        "guzzlehttp/guzzle": "~4.0" //you can change the version 
    }
}

让作曲家安装或更新

要使用guzzle创建第一个请求,下面的代码片段将起作用:

use GuzzleHttp\Client;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Message\Response;

$client = new Client();
$response = $client->get("https://api.github.com/");
retrun $response;

答案 4 :(得分:0)

首先运行此命令

作曲家需要吃惊http:// guzzle

use GuzzleHttp\Client;

    $client = new Client();
    $response = $client->get("http://www.somewebsite.com/getSmth");
    $response = (string) $response->getBody();
    return $response;

getBody()函数将返回对象。

您可以通过将其转换为字符串来使用,然后,如果需要,还可以将其更改为整数

    $response = (int) (string) $response->getBody();