使用Guzzle原始发送身体

时间:2018-08-07 06:39:16

标签: php http guzzle guzzle6

我正在尝试使用Guzzle将POST请求发送到我的Web服务。此服务接受原始的身体。当我使用邮递员但不使用Guzzle时,它工作正常。当使用Guzzle时,将Web服务URL放在浏览器中时,我只会得到Web服务描述。  这是我的代码:

    $body = "CA::Read:PackageItems  (CustomerId='xxxxxx',AllPackages=TRUE);";
    $headers = [
        ....
        ....

    ]; 
$client = new Client();
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',$headers,$body);
echo $body = $response->getBody();

似乎标题或正文未通过。

3 个答案:

答案 0 :(得分:0)

尝试这样

$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',['headers' => $headers, 'body' => $body]);

答案 1 :(得分:0)

我最近不得不第一次实现Guzzle,它是一个非常简单的库。

首先,我创建了一个新客户端

// Passed in our options with just our base_uri in
$client = new Client(["base_uri" => "http://example.com"]);

然后,我创建了一个POST请求,而不是我如何使用new Request而不是$client->request(...。不过,这对我使用new Request的影响并不大。

// Create a simple request object of type 'POST' with our remaining URI
// our headers and the body of our request.
$request = new Request('POST', '/api/v1/user/', $this->_headers, $this->body);

所以从本质上来说,它看起来像:

$request = new Request('POST', '/api/v1/user/', ['Content-Type' => "application/json, 'Accept' => "application/json], '{"username": "myuser"}');

$this->headers是我们请求标头的简单键值对数组,请确保设置Content-Type标头,而$this->body是简单的字符串对象,在我的情况下,它形成JSON身体。

然后我可以简单地调用$client->send(...方法来发送请求,例如:

// send would return us our ResponseInterface object as long as an exception wasn't thrown.
$rawResponse = $client->send($request, $this->_options);

$this->_options是一个简单的键-值对数组,它对headers而言仍然很简单,但这包括用于请求的timeout之类的东西。

对我来说,我创建了一个简单的Factory对象HttpClient,该对象为我构造了整个Guzzle请求,这就是为什么我只创建一个新的Request对象而不是调用$client->request(...也会发送请求。

答案 2 :(得分:0)

将数据作为原始数据发送时,本质上需要做的是对$data的数组进行json_encode并在请求body中发送。

$request = new Request(
    'POST',
    $url,
    ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
    \GuzzleHttp\json_encode($data)
);

$response = $client->send($request);
$content = $response->getBody()->getContents();

使用枪口请求GuzzleHttp\Psr7\Request;和客户端GuzzleHttp\Client