(编辑:jimmy 日期: 2024/11/17 浏览:2)
本文实例讲述了PHP实现支持GET,POST,Multipart/form-data的HTTP请求类及其应用,分享给大家供大家参考。具体如下:
HttpRequest.class.php类文件如下:
<"\r\n\r\n"); $response = substr($response, $pos+4); return $response; }else{ return false; } } // 创建连接 private function connect(){ $this->_fp = fsockopen($this->_ip, $this->_port, $this->_errno, $this->_errstr, $this->_timeout); if(!$this->_fp){ return false; } return true; } // 断开连接 private function disconnect(){ if($this->_fp!=null){ fclose($this->_fp); $this->_fp = null; } } // get 方式,处理发送的数据,不会处理文件数据 private function sendGet(){ // 检查是否空数据 if(!$this->_formdata){ return false; } // 处理url $url = $this->_url.'"GET ".$url." http/1.1\r\n"; $out .= "host: ".$this->_host."\r\n"; $out .= "connection: close\r\n\r\n"; return $out; } // post 方式,处理发送的数据 private function sendPost(){ // 检查是否空数据 if(!$this->_formdata && !$this->_filedata){ return false; } // form data $data = $this->_formdata"POST ".$this->_url." http/1.1\r\n"; $out .= "host: ".$this->_host."\r\n"; $out .= "content-type: application/x-www-form-urlencoded\r\n"; $out .= "content-length: ".strlen($data)."\r\n"; $out .= "connection: close\r\n\r\n"; $out .= $data; return $out; } // multipart 方式,处理发送的数据,发送文件推荐使用此方式 private function sendMultipart(){ // 检查是否空数据 if(!$this->_formdata && !$this->_filedata){ return false; } // 设置分割标识 srand((double)microtime()*1000000); $boundary = '---------------------------'.substr(md5(rand(0,32000)),0,10); $data = '--'.$boundary."\r\n"; // form data $formdata = ''; foreach($this->_formdata as $key=>$val){ $formdata .= "content-disposition: form-data; name=\"".$key."\"\r\n"; $formdata .= "content-type: text/plain\r\n\r\n"; if(is_array($val)){ $formdata .= json_encode($val)."\r\n"; // 数组使用json encode后方便处理 }else{ $formdata .= rawurlencode($val)."\r\n"; } $formdata .= '--'.$boundary."\r\n"; } // file data $filedata = ''; foreach($this->_filedata as $val){ if(file_exists($val['path'])){ $filedata .= "content-disposition: form-data; name=\"".$val['name']."\"; filename=\"".$val['filename']."\"\r\n"; $filedata .= "content-type: ".mime_content_type($val['path'])."\r\n\r\n"; $filedata .= implode('', file($val['path']))."\r\n"; $filedata .= '--'.$boundary."\r\n"; } } if(!$formdata && !$filedata){ return false; } $data .= $formdata.$filedata."--\r\n\r\n"; $out = "POST ".$this->_url." http/1.1\r\n"; $out .= "host: ".$this->_host."\r\n"; $out .= "content-type: multipart/form-data; boundary=".$boundary."\r\n"; $out .= "content-length: ".strlen($data)."\r\n"; $out .= "connection: close\r\n\r\n"; $out .= $data; return $out; } } // class end "htmlcode"><"_blank" href="http://xiazai.jb51.net/201409/yuanma/HttpRequest(jb51.net).rar">本站下载。希望本文所述对大家的PHP程序设计有所帮助。