I'm trying to make a POST request and send some values in the body of an API call. In the documentation of the API it says I need to make a POST request, using startUrls as an array with key and value.
<?php
$url = 'https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID';
$postData = array(
'startUrls' => array(array('key'=>'START', 'value'=>'https://instagram.com/instagram'))
);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'body' => json_encode($postData)
)
));
$resp = file_get_contents($url, FALSE, $context);
print_r($resp);
?>
The JSON seems to be how it should, but the script is not sending the body properly to the website.
According to the documentation, there is no body option for the HTTP context. Try content instead:
<?php
$url = "https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID";
$postData = [
"startUrls" => [
["key"=>"START", "value" => "https://instagram.com/instagram"]
]
];
$context = stream_context_create([
"http" => [
"method" => "POST",
"header" => "Content-type: application/json",
"content" => json_encode($postData)
]
]);
$resp = file_get_contents($url, FALSE, $context);
print_r($resp);
The following code will work. I have set the headers and specified the content type.
$request = new HttpRequest();
$request->setUrl('$url = 'https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'cache-control' => 'no-cache',
'content-type' => 'application/x-www-form-urlencoded'
));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array('key'=>'START', 'value'=>'https://instagram.com/instagram')
));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
If you want to try with cUrl the following code snippet will work.
$curl = curl_init();
$postData = array(
'startUrls' => array(array('key'=>'START', 'value'=>'https://instagram.com/instagram'))
);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"content-type: multipart/form-data;"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
Related
I'm performing a POST request to a REST Service that requires an OAuth 2.0 authorization.
In Postman everything works perfectly fine since enabling the "Follow Authorization header" option so the auth header will be retained after a redirection.
However I dont know the equivalent to that attribute for a CURL request in PHP. So therefore I still get the following error: "Session expired or invalid".
Does anyone know how to successfully keep the auth header after a redirection in PHP cURL?
This is my php code:
$token = $this->getToken();
$url = "XXX";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
,
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'client_id' => 'XXX',
'client_secret' => 'XXX',
'username' => 'XXX',
'password' => 'XXX',
'grant_type' => 'password',
'redirect_uri' => 'XXX'
)))
));
$response = curl_exec($curl);
var_dump('TOKEN: ' . $token);
var_dump($url);
var_dump(curl_getinfo($curl));
if (curl_errno($curl)) {
var_dump('Error:' . curl_error($curl));
} else {
var_dump("SUCCESS! ");
var_dump($response);
}
You cannot do this:
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'client_id' => 'XXX',
'client_secret' => 'XXX',
'username' => 'XXX',
'password' => 'XXX',
'grant_type' => 'password',
'redirect_uri' => 'XXX'
You already did this: URLOPT_POSTFIELDS => json_encode($data),
And you cannot use an array if you want to keep the Content-Type: application/json.
When you use an array for POSTFIELDS, curl will override the content type with Content-Type: application/x-www-form-urlencoded
I sometimes use file_get_content() with a context.
This is an easy way (without SSL) to get the headers and post data right.
Keeping mind that file_get_content() has some of the same idiosyncrasies as curl. The context has file_get_content() which populates the Body.
<?php
header("Content-Type: text/plain,UTF-8");
$jsn = file_get_contents('json.jsn');
$postdata = http_build_query(
array(
'json' => $jsn,
)
);
$opts = array('http' =>
array(
'method' => 'PUT',
'header' => 'Content-type: application/json',
'content' => $jsn //useing JSON rather than $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
echo $result;
I have been using the mail API to validate emails, but it has not returned the response. I am doing something wrong?
curl_setopt_array($this->curl, array(
CURLOPT_URL => "https://api.mailgun.net/v4/address/validate?address=".$email,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "address=".$email,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
"Authorization: Basic " . base64_encode("api:mikey")
),
));
$result=curl_exec ($this->curl);
error_log("result ". print_r($result, true));
$err = curl_error($this->curl);
curl_close($this->curl);
error_log("url: ".print_r($url, true));
error_log("error: ".print_r($err, true));
error_log("result: ".print_r($result, true));
return $result;
Well, I faced this same problem but using Guzzle 6.
You should put your account domain at the end of the API Base URL:
https://api.mailgun.net/v4/mysite.com
In Guzzle, these are my configurations (scripts in PHP):
$http_client = new Client([
'base_uri' => 'https://api.mailgun.net/v4/mysite.com',
'allow_redirects' => true,
'debug' => true, // for development purposes
'http_errors' => false
]);
This is the GET Request call:
$response = $http_client->request(
'get',
'address/validate',
[
'query' => ['address' => 'mail#mail.com']
'auth' => ['api', 'your_account_api_private_key'];
]
);
When trying to revoke the oauth access_token for Box, I get the error : Client id was not found in the headers or body
This is the curl-command (which works fine) :
curl https://api.box.com/oauth2/revoke -d 'client_id=CLIENT_ID&client_secret=CLIENT_SECRET&token=access_token' -X POST
When trying the same with php curl, I get the error.
<?php
$revokeurl="https://api.box.com/oauth2/revoke";
$dataq = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'token' => $access_token
);
$dataqjson= json_encode($dataq);
$headers=array(
"Content-Type: application/json"
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $revokeurl,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $dataqjson,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_SSL_VERIFYHOST => FALSE
));
$response = curl_exec($curl);
$json_response = json_decode( $response, TRUE );
curl_close($curl);
?>
Why is my POST with json body not correct ?
Data should be set as application/x-www-form-urlencoded rather than JSON-encoded. Example:
<?php
$revokeurl = "https://api.box.com/oauth2/revoke";
$dataq = array(
'client_id' => 'client_id',
'client_secret' => 'client_secret',
'token' => 'access_token',
);
$curl = curl_init();
curl_setopt_array(
$curl,
array(
CURLOPT_URL => $revokeurl,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($dataq),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
)
);
$response = curl_exec($curl);
$json_response = json_decode($response, false);
print_r($json_response);
curl_close($curl);
Im' looking to consume a Rest API using Zend Framework 2.
I tried :
How to consume a Rest API using Zend Framework 2
$request = new Request();
$request->getHeaders()->addHeaders(array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
));
$request->setUri($url);
$request->setMethod('POST');
$request->setPost(new Parameters(array('param1' => 'val1')));
$client = new Client($url, array(
'sslverifypeer' => null,
'sslallowselfsigned' => null,
));
$response = $client->dispatch($request);
$data = json_decode($response->getBody(), true);
Can someone provide an example how to enter username and password :
I tried this :
$request->getHeaders()->addHeaders(array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
'user' => 'username1',
'password' => 'password1'
));
From https://framework.zend.com/manual/2.4/en/modules/zend.http.client.advanced.html#http-authentication
$client->setAuth('username1', 'password1');
it works now, but with curl :
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "param1=value1",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded",
"password: password01",
"user: user01"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
<html>
<body><input type="button" id="send" value="Send"></body>
</html>
There'll be a button in my html,
When it's clicked, i'd like to connect to http://localhost:81/Help/Api/POST-Login
which is my api.
Then i'd like to post data to it.
Pretty confused now, any ideas guys. Thanks in advance
<?php
$url = "http://localhost:81/Help/Api/POST-Login";
$data = array(
'message' => 'hi,
mobile' => 12345678,
);
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
Use the below code to get the response from .NET API:
$url = "http://localhost:81/Help/Api/POST-Login";
$data = array( 'message' => 'hi, mobile' => 12345678,
);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST", //set request type post or get
CURLOPT_POST => false, //set to GET
CURLOPT_COOKIEFILE => "cookie.txt", //set cookie file
CURLOPT_COOKIEJAR => "cookie.txt", //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
$err = curl_errno($ch);
$errmsg = curl_error($ch);
$header = curl_getinfo($ch);
curl_close($ch);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
echo $header['content'];