當需要在PHP中通過url調用現有的java中的服務的時候,以下是一個簡單的demo範例。
核心代碼:調用函數
/**
* php通過url調用java服務
* Enter description here ...
* @param unknown_type $url
* @param unknown_type $data
*/
function _http_curl_post($url,$data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);
curl_setopt($ch, CURLOPT_TIMEOUT,4);
if($data){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "value=".json_encode($data)); //請求參數轉爲json格式
}
curl_setopt($ch, CURLOPT_HEADER, false);
$string = curl_exec($ch);
curl_close($ch);
return $string;
}
以下是一個調用上述函數的一個範例:
/**
* 調取用戶在睿道在線中的學習記錄,僅顯示前30條
* Enter description here ...
*/
public function neusoft(){
$uid = intval($_GET['uid']);
// $url="http://www.neuedu.cn/php/php!index.action?userId=".$uid;
$url="http://localhost:8080/NeuOnline/php/php!index.action?userId=10064";
$params = array();
// $params['userId'] = 1 ; 暫不起作用,待進一步探究
$data = $this->_http_curl_post($url,$params);
$list = json_decode($data,TRUE);
//dump($list);
$arrs=array_chunk($list,10); //每10條爲一組
$this->assign('list',$arrs[0]);// 賦值數據集
//dump($arrs);
//設置tab頁信息
$d['type'] = t($_GET['type']) ? t($_GET['type']) : 'neusoft';
$d['feed_type'] = t($_GET['feed_type']) ? t($_GET['feed_type']) : '';
$d['feed_key'] = t($_GET['feed_key']) ? t($_GET['feed_key']) : '';
// 判斷頻道是否開啓
$isChannelOpen = model('App')->isAppNameOpen('channel');
$this->assign('isChannelOpen', $isChannelOpen);
// 關注的頻道
if($isChannelOpen && $d['type'] === 'channel') {
$d['channelname'] = '我關注的頻道';
$d['channelGroup'] = D('ChannelFollow', 'channel')->getFollowList($this->mid);
foreach($d['channelGroup'] as $v) {
if($v['channel_category_id'] == t($_REQUEST['fgid'])) {
$d['channelname'] = $v['title'];
break;
}
}
}
$this->assign($d);
$this->assign("type","neusoft");
$this->assign("max",sizeof($arrs));
$this->display('index'); // 輸出模板
}
二、在java中調用php的action並傳遞參數
/**
* 調用指定的url,並且傳輸參數,獲取請求結果
*
* @param url
* @return
* @throws Exception
*/
public String connectionURL(String url,String param) throws Exception {
HttpURLConnection connection = null;
BufferedReader in = null;
StringBuffer sbinner=new StringBuffer();;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setReadTimeout(300*1000);
connection.setConnectTimeout(300*1000);
connection.setRequestProperty("Content-Length", Integer.toString(param.getBytes().length));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream outputStream = connection.getOutputStream();
final DataOutputStream printout = new DataOutputStream(outputStream);
printout.writeBytes(param);
printout.flush();
printout.close();
InputStream inputStream = connection.getInputStream();
in = new BufferedReader(new InputStreamReader(inputStream));
String lines;
sbinner = new StringBuffer();
while ((lines = in.readLine()) != null) {
sbinner.append(lines);
}
if (log.isDebugEnabled()) {
log.debug("Finished sending message to" + url);
}
} catch (Exception e) {
log.warn("Error Sending message to url endpoint [" + url + "]. Error is [" + e.getMessage() + "]");
}finally {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
// can't do anything
}
}
if (connection != null) {
connection.disconnect();
}
}
log.info(sbinner.toString());
return sbinner.toString();
}