【Android】手机端使用NanoHTTPD搭建服务器

序言

NanoHTTPD 是一个轻量级的 Java HTTP 服务器库,可以在应用程序中快速搭建一个简单的 HTTP 服务器。

准备工作

引入依赖

java 复制代码
implementation 'org.nanohttpd:nanohttpd:2.3.1'

添加网络访问权限

xml 复制代码
<uses-permission android:name="android.permission.INTERNET" />
搭建服务器

项目中创建一个名为 MyServer 的类,并继承自 NanoHTTPD。在该类中,实现 serve 方法来处理请求。

java 复制代码
import android.content.Context;

import fi.iki.elonen.NanoHTTPD;

import java.io.IOException;
import java.util.Map;

public class MyServer extends NanoHTTPD {

    private Context context;

    public MyServer(Context context) {
        super(8080);
        this.context = context;
    }

    @Override
    public Response serve(IHTTPSession session) {
        String uri = session.getUri();
        
        // 处理 GET 请求
        if (session.getMethod() == Method.GET) {
            switch (uri) {
                case "/hello":
                    return newFixedLengthResponse("Hello, World!");
                case "/time":
                    String currentTime = getCurrentTime();
                    return newFixedLengthResponse(currentTime);
                default:
                    return newFixedLengthResponse("Invalid path");
            }
        }
        
        // 处理 POST 请求
        if (session.getMethod() == Method.POST) {
            if ("/upload".equals(uri)) {
                try {
                    // 解析 POST 请求的参数
                    Map<String, String> files = session.getParms();
                    
                    // 处理上传的文件等逻辑
                    // ...
                    
                    return newFixedLengthResponse("Upload successful");
                } catch (IOException e) {
                    e.printStackTrace();
                    return newFixedLengthResponse("Upload failed: " + e.getMessage());
                }
            }
        }
        
        return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Not found");
    }
    
    private String getCurrentTime() {
        // 获取当前时间的逻辑
        // ...
        return "Current time: " + System.currentTimeMillis();
    }
}

在 serve 方法中,我们首先检查请求的方法,如果是 GET 方法,我们根据不同的路径返回不同的响应。例如,当访问 /hello 路径时,服务器将返回 "Hello, World!"。当访问 /time 路径时,服务器将返回当前时间。

如果是 POST 方法,并且路径为 /upload,则我们可以处理上传的文件等逻辑。在这个例子中,我们只是简单地返回上传成功或失败的消息。

最后,如果无法匹配到合适的路径,则返回 "Not found"。

启动服务器

创建 MyServer 的实例,并调用 start 方法来启动服务器。

java 复制代码
public class MainActivity extends AppCompatActivity {

    private MyServer server;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 创建服务器实例并启动
        server = new MyServer(this);
        try {
            server.start();
            Log.d("Server", "Server started");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 停止服务器
        if (server != null) {
            server.stop();
        }
    }
}

一旦服务器启动,可以在设备或模拟器上的浏览器中输入 http://localhost:8080/hellohttp://localhost:8080/time 等地址,来查看服务器返回的响应。

相关推荐
xywww1681 小时前
大模型 API 选型实战:GPT、Gemini、Claude 接入时该看哪些指标?
运维·服务器·人工智能·python·gpt·langchain
欢呼的太阳5 小时前
数据库设计Step by Step (10)——范式化
服务器·数据库·oracle
GoGeekBaird5 小时前
我开源了 BeeWeave,给 AI Agent 搭一个越用越懂你的知识创作台
后端·github
私人珍藏库5 小时前
[Android] PeakFinder AR v4.8.89 (山峰全景识别+增强现实山峰查看器)
android·人工智能·智能手机·ar·工具·软件
researcher-Jiang6 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
夜雪一千6 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
fthux7 小时前
GitZip Pro 源码解析:一个 GitHub 文件/文件夹下载扩展是如何工作的(一)整体架构与扩展入口
人工智能·ai·开源·github·open source
alexhilton7 小时前
Kotlin DSL深度解析:从Gradle脚本到构建你自己的DSL
android·kotlin·android jetpack
烽火聊员7 小时前
查看Android Studio错误日志
android·ide·android studio
第一程序员7 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github