近期項目,合做方所提供的數據通訊API,採用servlet服務端doPost()接收各項請求參數;雙方系統交互(請求/響應)均由後臺邏輯自動完成,即不經過FORM提交請求方式實現,所以後臺處理邏輯需模擬HTTP請求並使用POST方式向對方發送數據。ide
因在系統中經常使用,略爲筆記,PHP模擬POST請求代碼以下:ui
$host ="202.112.xxx.xxx";xml
$port =8099;ip
$path ='/servicepath';get
$cmd = "BALANCE";cmd
$userName="test"; servlet
//Build Request String it
$xml = '<?xml version="1.0"?>' ; io
$xml .= '<eload>' ; class
$xml .= '<command>'.$cmd .'</command>' ;
$xml .= '<userid>'.$userName.'</userid>' ;
$xml .= '</eload>' ;
$errno = '' ;
$errstr = '' ;
$time = date('His') ;
//Create Socket
$fp = fsockopen( $host, $port, $errno, $errstr, 10 ) or exit( $errstr."--->".$errno ) ;
$length = strlen( $xml ) ;
//Create Http Header with Post Method
$header = "POST http://".$host.":".$port.".$path."HTTP/1.1\r\n" ;
$header .= "Accept: */*\r\n" ;
$header .= "Accept-Language: zh-cn\r\n" ;
$header .= "Content-Type: text/xml; charset=ISO-8859-1\r\n" ;
$header .= "Accept-Encoding: gzip, deflate\r\n" ;
$header .= 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; ';
$header .= 'Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; ';
$header .= "NET CLR 3.0.30729; Media Center PC 6.0)\r\n" ;
$header .= "Host: ".$host.":".$port."" ;
$header .= "Content-Length: ".$length."\r\n" ;
$header .= "Connection: Keep-Alive\r\n" ;
$header .= "Pragma: no-cache\r\n\r\n" ;
//Link Request data
$header .= $xml."\r\n" ;
//Send Request
fputs( $fp, $header) ;
$inheader = 1 ;
while( !feof($fp) ){
$line = fgets( $fp, 1024 ) ;
//Get Response
if( $inheader && ($line == "\n" || $line == "\r\n") ){
$inheader = 0 ;
}
if($inheader == 0){
//echo $line ;
$result = $line;
}
}
//Clost Socket
fclose( $fp ) ;
相信仍有很多童鞋在此處困惑,特共享之~
Sky
343025026