分别测试了curl的get方法和post方法,发现get方法访问成功,post发送URL_encode形式的数据成功,
但是post方法发送json数据,接口提供方接收到的POST数据是空字符串.
后在网上发现了对应的解释,php接收数据时,默认只识别application/x-www.form-urlencoded标准的数据类型,修改头信息也没有结果。
解决方法是:$post = file_get_contents(“php://input”);
虽然不知甚解,但经过测试,访问的确成功了。需要接下来的学习中搞清楚原因。
-------------------------------------------
======服务端======
<?php
$wanwan = file_get_contents('php://input');
$wanwan = json_decode($wanwan);
$data = array(
'wanwan' => $wanwan,
'status' => 0
);
$str = json_encode($data);
exit($str);
-------------------------------------------
======调用端==============
$a = post('www.***.com/test.php',json_encode(array('a'=>'123')));
var_dump($a);
function post($url, $post, array $option = array()) {
$opts = array ();
$opts [CURLOPT_URL] = $url;
$outtime = 5 ;
$opts [CURLOPT_RETURNTRANSFER] = 1; //URL返回的内容作为curl_exec的返回值
$opts [CURLOPT_CONNECTTIMEOUT] = $outtime; //超?秒连不上则放弃
$opts [CURLOPT_TIMEOUT] = $outtime; //超?秒没有返回则放弃
if (! empty ( $post )) {
if (is_array ( $post )) {
$opts [CURLOPT_POSTFIELDS] = http_build_query ( $post, '', '&' );
} else {
$opts [CURLOPT_POSTFIELDS] = $post;
}
$opts [CURLOPT_POST] = 1;
}
if (parse_url ( $url, PHP_URL_SCHEME ) == 'https') {
$opts [CURLOPT_SSL_VERIFYHOST] = 2; // 2是推荐值, 详情见手册
$opts [CURLOPT_SSL_VERIFYPEER] = false;
}
if (! empty ( $option )) {
//$option,$opts的键名都是整数,不能用array_merge
foreach ( $option as $k => $v ) {
$opts [$k] = $v;
}
}
$ch = curl_init ();
curl_setopt_array ( $ch, $opts );
$res = curl_exec ( $ch );
curl_close ( $ch );
return $res;
}
function httpGet($url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}