how to pass data to JSON server using cURL with POST [duplicate] - php

I'm trying to POST some JSON to a web service with cURL, using the following code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, 'http://index.yolink.com/index/define?o=json&ak=APIKEY');
curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));
$data = array(
'ignore-robots' => 'false',
'language' => 'english',
'crawl-delay' => '0',
'depth' => '3',
'root' => array('url' => 'http://bartleby.com/')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result=curl_exec($ch);
var_dump($result);
I get the following in return:
string(282) "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Access-Control-Allow-Origin: * Content-Type: text/plain Content-Length: 120 Date: Fri, 18 Mar 2011 19:03:23 GMT {"code":"error.indexdefinition.invalid","message":"Invalid content provided for /define. Error:Premature end of file.."}"
I found this blog post that seems to be related -- it does seem to be sending text/plain even though I've specified the ContentType in CURLOPT_HTTPHEADERS as application/json. But adding http_build_query hasn't helped.
Thanks in advance for any help!

I believe it should be HTTPHEADER, not HTTPHEADERS.
http://php.net/manual/en/function.curl-setopt.php

Related

MailChimp integration Error code 501 - Unsupported request - PHP

Below is my code to add contact to the mailchimp. I am getting mailchimp api key and list id from the env file in laravel. Also $data involves all the input.
$apiKey = env('MAILCHIMP_APIKEY');
$listId = env('MAILCHIMP_LIST_ID');
$auth = base64_encode( 'user:'.$apiKey);
$mailChimpdata = array(
'apikey' => $apiKey,
'email_address' => $data['email'],
'status' => $data['status'],
'merge_fields' => array(
'FNAME' => $data['firstname'],
'LNAME' => $data['lastname']
)
);
$json_data = json_encode($mailChimpdata);
$ch = curl_init();
$memberId = md5(strtolower($data['email']));
$url = 'https://us19.admin.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
But I am getting this below error
HTTP/1.0 501 Not Implemented
Server: AkamaiGHost
Mime-Version: 1.0
Content-Type: text/html
Content-Length: 334
Expires: Wed, 07 Apr 2021 08:49:45 GMT
Date: Wed, 07 Apr 2021 08:49:45 GMT
Connection: close
Set-Cookie: _abck=471ED28A26F6757CE57AC9E4318E7BD6~-1~YAAQHdcLF/keKqt4AQAASPOFqwWS/EeAKXso+2igviRTfIMw3pqbDMndhfZPfoX+eQn3Iv8iqfbogtNFmkU4lRDRQLdAWAYBhq2oOhDTiK ▶
Set-Cookie: bm_sz=5CBD698E96AC9E2B62898990FF45E196~YAAQHdcLF/oeKqt4AQAASPOFqwsLVm8fKmxtToeWU99vCUWske+XMuRtEjiCpzXhPE5xe8jGoh6EfYe8WG6zjMaaI2jPZos0gb2ER9jykveOE ▶
<HTML><HEAD>
<TITLE>Unsupported Request</TITLE>
</HEAD><BODY>
<H1>Unsupported Request</H1>
PUT to http://us19.admin.mailchimp.com/3.0/lists/applevendor/members/b642b4217b34b1e8d3bd915fc65c4452 not supported.<P>
Reference #8.1dd70b17.1617785385.68d39e
</BODY></HTML>
Please help me out to resolve this issue.
Based on Mailchimp documentation they use URL to add contact
"https://us20.api.mailchimp.com/3.0/lists/$list_id/members/"
but you have
"https://us19.admin.mailchimp.com/3.0/lists/$listId/members/$memberId"
with $memberId. I guess that id is their internal identificator.
I don't know if this topic is still relevant but here is my method using php / Guzzle:
$client = new Client();
$client->request('PUT', 'https://us9.api.mailchimp.com/3.0/lists/{list_id}/members/{subscriber_hash},
[
'json' => [
'email_address' => $email,
'status_if_new' => "unsubscribed",
],
'headers' => [
"Authorization" => "Basic YOUR_API_KEY"
]
]);
subscriber_hash => hash MD5

SkyScanner API error when called by PHP

I did exactly as shown in the API documentation
http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingList
but when i call it returns this error
HTTP/1.1 100 Continue HTTP/1.1 500 Internal Server Error Cache-Control: private Content-Type: application/json Date: Sat, 04 Jun 2016 06:23:48 GMT Connection: close Content-Length: 2 {}
and here is my code in PHP
<?
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0/';
$data = array('apiKey' => 'de995438234178656329029769192274', 'country' => 'BR', 'currency' => 'BRL',
'locale' => 'pt-BR', 'originplace' => 'SDU-iata', 'destinationplace' => 'GRU-iata', 'outbounddate' => '2016-09-23',
$headers = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
printf($result);
?>
any idea what is going wrong?
thanks in advance for any kind
So I think the PHP is sending the wrong request type, because the HTTP headers were being sent as an array (so defaults to 'multipart/formdata'). If you use http_build_query on that array, it is sent correctly as 'x-www-form-urlencoded'.
I've tidied things up, removed some duplication in the curl options, and correctly get a 201 response on your example now:
<?
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0/';
$data = array('apiKey' => 'de995438234178656329029769192274', 'country' => 'BR', 'currency' => 'BRL',
'locale' => 'pt-BR', 'originplace' => 'SDU', 'destinationplace' => 'GRU', 'outbounddate' => '2016-09-23', 'locationschema' => 'Iata', 'adults' => 1);
$httpdata = http_build_query($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $httpdata);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>
Hope that helps, I'll keep an eye on the thread in case of anything else - feel free to drop us a query or check the FAQs here: https://support.business.skyscanner.net/hc/en-us

Share the same cookie between two PHP requests with cURL

My first post here... I am handling cookies between get/post pair of requests.
Based on this other question:
share the same cookie between two website using PHP cURL extension
Is my approach correct?
<?php
//set POST variables
$referer = 'http://www.correios.com.br/encomendas/prazo/';
$url = 'http://www.correios.com.br/encomendas/prazo/prazo.cfm';
$fields = array(
'Altura' => '8',
'Comprimento' => '16',
'Formato' => '1',
'Largura' => '15',
'MaoPropria' => 'N',
'avisoRecebimento' => 'N',
'cepDestino' => '99999999',
'cepOrigem' => '99999999',
'data' => '02/12/2012',
'dataAtual' => '02/12/2012',
'embalagem' => '',
'peso' => '1',
'resposta paginaCorreios'=> '',
'servico' => '99999',
'valorD' => '',
'valorDeclarado'=> ''
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, '10');
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');
// Post 1
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_URL, $referer);
$result = trim(curl_exec($ch));
//
$ch = curl_init($url);
//Post 2
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_REFERER, $referer);
//execute post
$result = curl_exec($ch);
//
//close connection
curl_close($ch);
echo($result);
?>
What I need is mimic this behavior:
Response Headers:
Content-Type text/html; charset=ISO-8859-1
Date Sun, 02 Dec 2012 20:13:08 GMT
Server Microsoft-IIS/7.5
Set-Cookie JSESSIONID=c6308c7edb989a54edef1b656119101c321b;path=/ CFGLOBALS=urltoken%3DCFID%23%3D33736896%26CFTOKEN%23%3D28355865%26jsessionid%23%3Dc6308c7edb989a54edef1b656119101c321b%23lastvisit%3D%7Bts%20%272012%2D12%2D02%2018%3A13%3A09%27%7D%23timecreated%3D%7Bts%20%272012%2D12%2D02%2002%3A13%3A29%27%7D%23hitcount%3D6%23cftoken%3D28355865%23cfid%3D33736896%23;expires=Tue, 25-Nov-2042 20:13:09 GMT;path=/
Transfer-Encoding chunked
Request Headers:
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3
Connection keep-alive
Cookie CFID=33736896; CFTOKEN=28355865; CFGLOBALS=urltoken%3DCFID%23%3D33736896%26CFTOKEN%23%3D28355865%26jsessionid%23%3D983074629e3d7344ff534b12637b7f127163%23lastvisit%3D%7Bts%20%272012%2D12%2D02%2002%3A56%3A48%27%7D%23timecreated%3D%7Bts%20%272012%2D12%2D02%2002%3A13%3A29%27%7D%23hitcount%3D5%23cftoken%3D28355865%23cfid%3D33736896%23
Host www.correios.com.br
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:17.0) Gecko/20100101 Firefox/17.0
Reading from some others topics, I have learned about multi_exec:
PHP cURL multi_exec delay between requests
I mean, what is the correct approach for the this task?
Thanks in advance!
Renato

Ignore Content-Type: application/force-download in CURL

I need to read the size of a file but the server is forcing me to download it first.
I note one of the response headers is Content-Type: application/force-download and that seems to bypass my curl inputs...
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch,CURLOPT_TIMEOUT,1000);
curl_exec($ch);
$bytes = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
Any ideas?
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
These two lines reset CURLOPT_NOBODY.
CURLOPT_NOBODY changes method to HEAD and CURLOPT_POST changes it to POST.
Source: http://php.net/manual/en/function.curl-setopt.php
Curl conforms with the force-download header, but file_get_contents can be used to limit the file download download to only 1 byte. This solved the problem!
$postdata = http_build_query(
array(
'username' => "",
'password' => ""
)
);
$params = array(
'http' => array
(
'method' => 'POST',
'header'=>"Content-type: application/x-www-form-urlencoded\r\n",
'content' => $postdata
)
);
$ctx = stream_context_create($params);
file_get_contents($url,false,$ctx,0,1);
$size = str_replace("Content-Length: ","",$http_response_header[4]);

Content-type not changing with CURLOPT_HTTPHEADERS

I'm trying to POST some JSON to a web service with cURL, using the following code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, 'http://index.yolink.com/index/define?o=json&ak=APIKEY');
curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));
$data = array(
'ignore-robots' => 'false',
'language' => 'english',
'crawl-delay' => '0',
'depth' => '3',
'root' => array('url' => 'http://bartleby.com/')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result=curl_exec($ch);
var_dump($result);
I get the following in return:
string(282) "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Access-Control-Allow-Origin: * Content-Type: text/plain Content-Length: 120 Date: Fri, 18 Mar 2011 19:03:23 GMT {"code":"error.indexdefinition.invalid","message":"Invalid content provided for /define. Error:Premature end of file.."}"
I found this blog post that seems to be related -- it does seem to be sending text/plain even though I've specified the ContentType in CURLOPT_HTTPHEADERS as application/json. But adding http_build_query hasn't helped.
Thanks in advance for any help!
I believe it should be HTTPHEADER, not HTTPHEADERS.
http://php.net/manual/en/function.curl-setopt.php

Categories