I'm trying to send a post request that header is json and the response also is json. What i have tried so far. This always return a status code 400. what i'm doing wrong?Thanks
private function requestPOST($url,$data)
{
App::uses('HttpSocket', 'Network/Http');
App::uses('Json', 'Utility');
$this->layout = 'default';
$this->autoRender = true;
$HttpSocket = new HttpSocket();
$jsonData = json_encode($data);
$request = array('header' => array('Content-Type' => 'application/json'));
debug($url);
$response = $HttpSocket->post($url, $jsonData, $request);
debug($response->code);
//$this->render('index');
$jsonString = json_decode($response['body'], true);
debug($jsonString);
return $jsonString;
}
I have solved myself. I was doing twice json_encode of the $data.
Related
How to modify this response
$url = "https://example.com";
$data = "{\"phone_number\":\"18868768"};
$len = strlen($data);
$headers = array();
$otp = request($url, $data, $headers);
the response is
{"status":0,"msg":"not Found"}
I want to modify to this :
{"status":1,"msg":"Found"}
I'll assume you're saving your response to a $response variable. You need to convert the JSON to an array to manipulate it, then convert it back to JSON. So to change it you would do:
$response = json_decode($response, true);
$response['status'] = 1;
$response['msg'] = 'Found';
$response = json_encode($response);
That being said, you really shouldn't be encoding your initial JSON in string form. Do this instead:
$data = json_encode([
'phone_number' => 18868768
]);
I want CakePHP to stream a download to the browser. The content of the stream is served via an API.
So, CakePHP makes a request to that API, gets a response with a file and must stream this response to the browser.
This is what I got so far:
public function getDownload() {
// do other things
$http = new Client([
'headers' => [
'accept' =>'application/octet-stream'
]
]);
$response = $http->get($this->url,[]);
// first try
// $stream = new CallbackStream(function () use ($response) {
// return $response;
// });
// $response = $response->withBody($stream);
// second try
// $stream = new CallbackStream($http->get($this->url,[])->getData());
// $response = $response->withBody($stream);
return $response;
}
With this setup I can download small files. The reason I need a stream is, because the API could send files up to 10GB. My guess is, that with $http->get CakePHP stores the whole response in memory. Thats why I'm getting a memory exhausted error.
I know I'm lacking a bit of understanding here. Any help is appreciated :)
Finally I found a solution:
public function getDownload($url) {
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"accept: application/octet-stream\r\n"
)
);
$context = stream_context_create($opts);
$response = new Response();
$file = fopen($url, 'r',false, $context);
$stream = new CallbackStream(function () use ($file) {
rewind($file);
fpassthru($file);
fclose($file);
});
$response = $response->withBody($stream);
return $response;
}
I am trying to send my form data from one domain to another domain using API with Guzzle HTTP.
But when I am sending any file field that time it gives me error.
My First server Code
$inputs = $request->all();
$scan_2 = 'user_scan_2_' . $request->file('fileToUpload')->getClientOriginalExtension();
$destination = base_path() . '/public/files/uploaded/user/temp/';
$request->file('fileToUpload')->move($destination, $scan_2);
$inputs['fileToUpload'] = $this->makeCurlFile($destination.'/'.$scan_2);
$response = Http::post('"http://msite.test/api/test', $inputs,$headers);
My Guzzle Code Over HTTP facade
public function send($method, $url, $data, $headers = ["Content-Type" => "application/json"]) {
$method = strtoupper($method);
$contentType = $headers['Content-Type'] ?? ($headers['content-type'] ?? '');
$requestData['headers'] = $headers;
if(in_array($method, ['GET', 'DELETE'])){
$requestData['query'] = $data;
}elseif(in_array($method, ['POST','PUT', 'PATCH'])){
switch(strtolower($contentType)){
case 'application/json':
$requestData['json'] = $data;
break;
case 'application/x-www-form-urlencoded':
$requestData['form_params'] = $data;
break;
case 'multipart/form-data':
$requestData['multipart'] = $data;
break;
default:
$requestData['body'] = $data;
break;
}
}
$response = $this->client->request($method, $url, $requestData);
return $response;
}
public function post($url, $data = [], $headers = ["Content-Type" => "application/json"]) {
return $this->send('post', $url, $data, $headers);
}
I am using content type as multipart/form-data
Now when I run my code that time got error
Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string given, called in
Hi I am new to Laravel and have tried several turtorials on Goutte on Guzzelhttp but I am still unable to figure out how to remove 3 unwanted charactures from the begining of the json responce as shown here using curl and json_decode.
$url = "URL to atom feed";
$user = "user";
$pass = "pass";
// using CURL to get our results
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
$output = curl_exec($ch);
curl_close($ch);
// decoding our results into an associative array
// doing a substring as there are 3 weird characters being passed back from IIS in front of the string
$data = json_decode(substr($output, 3, strlen($output)), true);
// grabbing our results object
$list = $data['$resources'];
I have in my ScrapeController,
<?php
// app/controllers/ScrapeController.php
class ScrapeController extends BaseController {
public function getIndex() {
echo "Scrape index page.";
}
public function getNode($node) {
echo "Scraped page $node";
}
public function getPages() {
$client = new GuzzleHttp\Client();
$res = $client->get('URL to atom feed', ['auth' => ['user', 'pass']]);
echo $res->getStatusCode();
// "200"
// echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
this is what I have tried $res->getBody(substr($res, 3, strlen($res));without any luck I am unable to find any answers to this problem on guzzle documents page save to say any custom json_decode option should be preformed in the getBody() option.
You need to do
$body = substr($res->getBody(), 3)
instead of
$body = $res->getBody(substr($res, 3, strlen($res))
I recently found this piece of code on github by Colin Viebrock,
$client = new Guzzle\Http\Client('http://example.com');
$client->addSubscriber( new Cviebrock\Guzzle\Plugin\StripBom\StripBomPlugin() );
$request = $client->get('some/request');
$response = $client->send($request);
$data = $response->json();
works a treat in laravel hope this helps anyone how gets "Unable to parse response body into JSON: 4" using Guzzle.
Http post return data with invalid characters
$url = 'https://sandbox.itunes.apple.com/verifyReceipt';
$params = array('receipt-data' => 'receipt data');
$params = json_encode($params);
my code is
$client = new Client();
$client->setUri($url);
$client->setMethod('POST');
$client->setRawBody($params);
$client->setHeaders(array(
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
));
$client->setAdapter(new Curl());
$response = $client->send();
$res = $response->getContent();
my out put is this
����
if any one know about this please help me.
You have to decode JSON response from the body like this:
var_dump(json_decode($response->getBody(), true));
Then you will get an array with proper response :)
e.g.:
array(1) { ["status"]=> int(21002) }