I have the following code that is currently used on an SDK for an integration and I want to migrate this to using Guzzle PHP for a cleaner and simplified code.
<?php
class Request
{
private $is_last_session_id;
public function send($s_url, $data)
{
$params = [
'http' => [
'method' => 'POST',
'content' => $data,
'header' => "Content-type: application/x-www-form-urlencoded",
],
];
$ctx = stream_context_create($params);
ini_set('user_agent', 'PHP Client /5.2.00');
$fp = fopen($s_url, 'rb', false, $ctx);
$response = stream_get_contents($fp);
$meta = stream_get_meta_data($fp);
foreach (array_keys($meta) as $h) {
$v = $meta[$h];
if (is_array($v)) {
foreach (array_keys($v) as $hh) {
$vv = $v[$hh];
if (is_string($vv) && substr_count($vv, 'JSESSIONID')) {
$this->is_last_session_id = substr($vv, strpos($vv, '=') + 1, 24);
}
}
}
}
return $response;
}
}
Here is the code that uses Guzzle
private function guzzleRequest($uri, $data)
{
$client = new \GuzzleHttp\Client();
$client->request('POST', $uri, [
'form_params' => $data,
'headers' => [
'Content-type' => 'application/x-www-form-urlencoded',
],
]);
}
From the code, I understand that it is doing a POST request, but when I try to use Guzzle's $client->post()
or $client->request('POST',$data)
with the specific headers as per the code above, I get a 500 server error. The above code as is works fine. Am I missing something when calling the methods using Guzzle?
This should be as simple as:
$client = new \GuzzleHttp\Client();
$client->request('POST', $uri, ['form_params' => $data]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.