博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
php 创建简单的Restful WebAPI(三)
阅读量:4680 次
发布时间:2019-06-09

本文共 3661 字,大约阅读时间需要 12 分钟。

  上篇记录了怎样实现route,本篇记录怎么实现request,response。

  Request 处理请求

request_vars = array(); $this->data = array(); $this->http_accept = 'application/json'; $this->method = 'get'; $this->ID = $id; $this->processRequest(); } public function processRequest() { $request_method = strtolower($_SERVER['REQUEST_METHOD']); $this->setMethod($request_method); $request_vars = $_GET; if($request_vars != ''){ $this->setRequestVars($request_vars); } $data = file_get_contents('php://input'); if($data != ''){ $this->setData(json_decode($data,TRUE)); } } public function setID($id) { $this->ID = $id; } public function setData($data) { $this->data = $data; } public function setMethod($method) { $this->method = $method; } public function setRequestVars($request_vars) { $this->request_vars = $request_vars; } public function getID() { return $this->ID; } public function getData() { return $this->data; } public function getMethod() { return $this->method; } public function getHttpAccept() { return $this->http_accept; } public function getRequestVars() { $this->request_vars['id'] = $this->ID; return $this->request_vars; } } ?>

  代码十分简单,就是从request获取请求method,querystring,请求body数据(json格式)。

  Response 发送响应

getStatusCodeMessage($status); header($status_header); header('Content-type: ' . $content_type . '; charset=utf-8'); echo $body; exit; } public function getStatusCodeMessage($status) { $codes = Array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '(Unused)', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported' ); return (isset($codes[$status])) ? $codes[$status] : ''; }} ?>

  生成response。

  这两个类为工具类,实现也不复杂,功能单一,需要继续丰富修改。

转载于:https://www.cnblogs.com/coldlern/p/3954569.html

你可能感兴趣的文章