I am using laravel guzzle package for get response from this https://eos.greymass.com/v1/history/get_transaction url
$client = new Client();
try {
$response = $client->request('GET', 'https://eos.greymass.com/v1/history/get_transaction?id=18a20dbc34082451143c03ac54a2f24d06494d51e68f8fb1211ca0b63a53f37d');
}catch (ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
return redirect()->back()->with('error', $responseBodyAsString);
}
if ($response->getStatusCode() != 200){
return redirect()->back()->with('error', 'Status code must be 200');
}
$body = $response->getBody();
return $body;
I get $body data properly, but when i tried to get $body->block_num then showing me this Undefined property: GuzzleHttp\Psr7\Stream::$block_num error
You have to decode the $response to get it as because it will convert json into an object
So for example:
$response = json_decode($client->request('GET', 'https://eos.greymass.com/v1/history/get_transaction?id=18a20dbc34082451143c03ac54a2f24d06494d51e68f8fb1211ca0b63a53f37d')->getBody(), true);
Try This! It will Help You
Related
Currently I only can send a get request to the url, but how do i safe the requested data to my database?:
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://xxxx.de/data');
echo $res->getStatusCode();
echo $res->getHeader('content-type')[0];
echo $res->getBody();
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://xxxx.de/data');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
I am sending a POST request to an API, Curl returns 200 and the correct response.
When Implementing with GuzzleHttp\Client, I get a 400 Bad request, what is wrong with my formatting.
here is my code using Laravel Returns 400 Bad Request:
$client = new Client();
$URI = 'http://api.example.com';
$params['headers'] = ['Content-Type' => 'application/json',
'apikey' => config('app._api_key'),
'debug' => true
];
$params['form_params'] = [
'sender' => 'Test_sender',
'recipient' => config('app.test_recipient'),
'message_body' => 'Test body'
];
return $response = $client->post($URI, $params);
Curl (Returns 200):
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'apikey: 212121212’ -d '{ "message_body": "test","sender": "2018","recipient": “4453424141” }' 'http://api.example.com'
Try the below code:
$client = new \GuzzleHttp\Client(['headers' => ['Content-Type' => 'application/json',
'apikey'=> config('app._api_key'),
'debug' => true
]
]);
$URI = 'http://api.example.com';
$body['sender']='Test_sender';
$body['recipient']=config('app.test_recipient');
$body['message_body']='Test body';
$body=json_encode($body);
$URI_Response = $client->request('POST',$URI,['body'=>$body]);
$URI_Response =json_decode($URI_Response->getBody(), true);
return $URI_Response;
Note: I would suggest you to handle error please refer GuzzleDocumentation
That is proper error handling:
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
try {
$response = $client->get(YOUR_URL, [
'connect_timeout' => 10
]);
// Here the code for successful request
} catch (RequestException $e) {
// Catch all 4XX errors
// To catch exactly error 400 use
if ($e->getResponse()->getStatusCode() == '400') {
echo "Got response 400";
}
// You can check for whatever error status code you need
} catch (\Exception $e) {
// There was another exception.
}
Implementation: http://guzzle.readthedocs.org/en/latest/quickstart.html
You can handle errors like this
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Exception;
try{
$client = new Client();
$response = $client->request('POST', $url,[
'headers' => $header,
'form_params' => $form-params
]);
$body = $response->getBody();
$status = 'true';
$message = 'Data found!';
$data = json_decode($body);
}catch(ClientException $ce){
$status = 'false';
$message = $ce->getMessage();
$data = [];
}catch(RequestException $re){
$status = 'false';
$message = $re->getMessage();
$data = [];
}catch(Exception $e){
$this->status = 'false';
$this->message = $e->getMessage();
$data = [];
}
return ['status'=>$status,'message'=>$message,'data'=>$data];
With this code,
$client = new \GuzzleHttp\Client(['base_uri'=> 'http://example.com']);
try{
$data = ['params1'=>'value1', 'params2'=> 'value2'];
$res = $client->request('GET', '/', ['query'=> $data]);
}catch(\GuzzleHttp\Exception\RequestException $e)
{
echo $e->getRequest()->getUri();
}
This is output :
http://example.com/?params1=value1params2=value2
You can see absence of ampersand in the string queries of request uri !
How resolve this problem ?
This should do it
$client = new \GuzzleHttp\Client(['base_uri'=> 'http://example.com']);
try{
$data = ['params1'=>'value1', 'params2'=> 'value2'];
$res = $client->request('GET', '/', ['query'=> http_build_query($data)]);
}catch(\GuzzleHttp\Exception\RequestException $e)
{
echo $e->getRequest()->getUri();
}
This was a bug fixed in the 6.0.1 version. Please, use a stable version of guzzle, and your code will works.
I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??
I have a little php api client with this method:
private function send($endpoint)
{
$headers = array();
$body = $this->xmlSerialiser->convertToXML($this->getQueue());
try {
$response = json_decode(
$this->guzzleClient->post(
$endpoint,
$headers, $body
)
->send()
->json()
);
} catch (\Guzzle\Http\Exception\BadResponseException $e) {
$response = array('Error' => $e->getMessage());
}
return $response;
}
I'm always receiving
Unable to parse response body into JSON: 4 (500 Internal Server Error)
I already tried to know an example of server response and seems to be fine:
echo (string) $this->guzzleClient->post(
$endpoint,
$headers, $body
)
->send()->getBody();
and this is the result:
<Messages xmlns="http://www.example.com/xxx/3.0">
<GetAccountResponse RequestType="GetAccount">
<AccountId>xxxx-xxx-xxx-xxxx-xxxx</AccountId>
<Token>xxxxxxxxxxxxxx/t3VkEJXC7f6b6G4yPJSZ5QfT2hdSQXUmi0e8cndSYLK4N7mswRHifzwGHLUJYHM17iGL8s=</Token>
</GetAccountResponse>
I answered myself
the Guzzle documentation says: json method -> Parse the JSON response body and return an array
so in my case I need to switch the json mehod to xml (cos the response is an xml).
Finally this is the result:
private function send($endpoint)
{
$headers = array();
$body = $this->xmlSerialiser->convertToXML($this->getQueue());
try {
$response = (array)(
$this->guzzleClient->post(
$endpoint,
$headers, $body
)
->send()
->xml()
);
} catch (\Guzzle\Http\Exception\BadResponseException $e) {
$response = array('Error' => $e->getMessage());
}
return $response;
}
Use following code.
$response->getBody()->getContents()