Record a crazy experience of requesting data with curl

Source: Internet
Author: User

# # # I need to use curl to request in JSON format,

curl_setopt ($ch, curlopt_httpheader,[]); /* START I set up an associative array, so always error, look closely at the document, should be indexed data [' Content-type:application/json ']

The array type of curlopt_postfields should be json_encode, otherwise the interface cannot be received.

/*
*curl Post
*content-type:application/json
*var $url String
*var $postData Array
*/
function Curl_post ($url, $postData) {
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, curlopt_returntransfer,true);
curl_setopt ($ch, curlopt_header,true);
curl_setopt ($ch, Curlopt_connecttimeout, 5);
curl_setopt ($ch, Curlopt_timeout, 30);
curl_setopt ($ch, Curlopt_post, true);
curl_setopt ($ch, Curlopt_postfields,json_encode ($postData));
curl_setopt ($ch, curlopt_httpheader,[
' Content-type:application/json ',
' Connection:keep-alive '
]);
$output = curl_exec ($ch);
$response = Array ();
$errorCode = Curl_errno ($ch);
if ($errorCode) {
return false;
} else {
$httpCode = Curl_getinfo ($ch, Curlinfo_http_code);
$header _size = Curl_getinfo ($ch, curlinfo_header_size);
$header _text = substr ($output, 0, $header _size);
$body = substr ($output, $header _size);
$headers = Array ();
foreach (Explode ("\ r \ n", $header _text) as $i = + $line) {
if (!empty ($line)) {
if ($i = = = 0) {
$headers [' http_code '] = $line;
} else if (Strpos ($line, ":")) {
List ($key, $value) = Explode (': ', $line);
$headers [$key] = $value;
}
}
}
$response [' headers '] = $headers;
$response [' body '] = $body;
$response [' http_code '] = $httpCode;
}
Curl_close ($ch);
return $response;
}

Record a crazy experience of requesting data with curl

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.