Android NanoHTTPD 是一个轻量级的 HTTP 服务器,用于在 Android 设备上运行 Web 服务
try { // 处理 HTTP 请求的代码 } catch (IOException e) { // 处理异常的代码 }
sendError()
方法发送错误响应。例如,返回一个 404 Not Found 错误:response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
Log
类记录错误信息:Log.e("NanoHTTPD", "Error processing request", e);
assets
或 res/raw
目录下,然后根据错误代码返回相应的页面。例如,为 404 Not Found 错误返回自定义错误页面:
try { // 处理 HTTP 请求的代码 } catch (IOException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found"); try { InputStream inputStream = getAssets().open("404.html"); OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); outputStream.write(buffer); outputStream.flush(); outputStream.close(); inputStream.close(); } catch (IOException ex) { Log.e("NanoHTTPD", "Error serving custom 404 page", ex); } }
通过以上方法,可以有效地处理 Android NanoHTTPD 中的错误。