PHP与java接口对接使用json格式请求

PHP与java接口对接使用json格式请求

$datajson = json_encode($param);
$myheader= array(
		'Content-Type: application/json; charset=utf-8',
		'Content-Length: ' . strlen($datajson)
);
$result = http_curl($url, 'xml', $datajson, 6, FALSE, '',$myheader);

function http_curl($url, $method, $params, $timeout=10, $https=FALSE, $isReturnHead='', $curlheader=''){
	$curl = curl_init();
	
	$parastr = '';
	if(strtolower($method) == 'xml'){
		$parastr = $params;
	}else{
		if(!empty($params)){
			foreach ($params as $key => $value) {
				$parastr .= $key . '=' . urlencode($value) . '&';
			}
			$parastr = substr($parastr, 0, -1);
		}
	}
	
	if(strtolower($method) == 'post' || strtolower($method) == 'xml'){
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $parastr);
	}else{
		curl_setopt($curl, CURLOPT_URL, $url . '?' . $parastr);
	}
	if($https){
		curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, FALSE);
	}
	if($isReturnHead){//返回response头部信息
		curl_setopt($curl, CURLOPT_HEADER, 1);   
	}else{
		curl_setopt($curl, CURLOPT_HEADER, 0);
	}
	if($curlheader){
		curl_setopt($curl,CURLOPT_HTTPHEADER,$curlheader);
	}
	curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout - 1);
	//调试时打开
	//curl_setopt($curl, CURLINFO_HEADER_OUT, true);
	
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$resp['body'] = curl_exec($curl);
	$resp['code'] = trim(curl_getinfo($curl, CURLINFO_HTTP_CODE));
	//$resp['debug'] = curl_getinfo($curl);
	$errno = curl_errno($curl);
	if($errno != 0){
		$resp['code'] = $errno;
		$resp['body'] = curl_error($curl);
	}
	curl_close($curl);
	return $resp;
}

$curlheader = array('Content-Type:application/x-www-form-urlencoded;charset=utf-8');

posted on 2020-05-07 17:31  aworkstory  阅读(1059)  评论(0编辑  收藏  举报

导航