赞
踩
NanoHTTPD 是一个轻量级的 Java HTTP 服务器库,可以在应用程序中快速搭建一个简单的 HTTP 服务器。
引入依赖
implementation 'org.nanohttpd:nanohttpd:2.3.1'
添加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
项目中创建一个名为 MyServer 的类,并继承自 NanoHTTPD。在该类中,实现 serve 方法来处理请求。
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 方法来启动服务器。
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/hello 或 http://localhost:8080/time 等地址,来查看服务器返回的响应。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。