package com.hdl.photovoltaic.internet.HttpServer; import android.text.TextUtils; import com.alibaba.fastjson.JSON; import com.hdl.photovoltaic.other.HdlFileLogic; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import fi.iki.elonen.NanoHTTPD; /** * 本地服务器 */ public class MyNanoHttpServer extends NanoHTTPD { //声明服务端 端口 public static final Integer HTTP_PORT = 49152; public MyNanoHttpServer(String hostname, int port) { super(hostname, port); } private volatile static MyNanoHttpServer myNanoHttpServer; //TODO 单例模式,获取实例对象,并传入当前机器IP public static MyNanoHttpServer getInstance(String ipAddress) { if (myNanoHttpServer == null) { synchronized (MyNanoHttpServer.class) { if (myNanoHttpServer == null) { myNanoHttpServer = new MyNanoHttpServer(ipAddress, HTTP_PORT); } } } return myNanoHttpServer; } @Override public Response serve(IHTTPSession session) { //TODO 解决客户端请求参数携带中文,出现中文乱码问题 ContentType ct = new ContentType(session.getHeaders().get("content-type")).tryUTF8(); session.getHeaders().put("content-type", ct.getContentTypeHeader()); return dealWith(session); } private Response dealWith(IHTTPSession session) { Date dateTime = new Date(); if (Method.POST == session.getMethod()) { //获取请求头数据 Map header = session.getHeaders(); //获取传参参数 Map params = new HashMap(); try { session.parseBody(params); String paramStr = params.get("postData"); if (TextUtils.isEmpty(paramStr)) { return newFixedLengthResponse("success"); } paramStr = paramStr.replace("\r\n", " "); com.alibaba.fastjson.JSONObject jsonParam = JSON.parseObject(paramStr); Map result = new HashMap<>(); //TODO 写你的业务逻辑..... //升级驱动文件路径 String fileName = ((HTTPSession) session).getUri(); String data = ""; if (fileName.equals(HdlFileLogic.getInstance().getDriveRootPath())) { data = HdlFileLogic.getInstance().readFile(fileName); } //响应客户端 return newFixedLengthResponse(data); // return newFixedLengthResponse("success"); } catch (IOException e) { e.printStackTrace(); } catch (ResponseException e) { e.printStackTrace(); } return newFixedLengthResponse("success"); } else if (Method.GET == session.getMethod()) { Map> parameters = session.getParameters(); //升级驱动文件路径 String fileName = ((HTTPSession) session).getUri(); String data = ""; if (fileName.contains(HdlFileLogic.getInstance().getDriveRootPath())) { data = HdlFileLogic.getInstance().readFile(fileName); } //响应客户端 return newFixedLengthResponse(data); // return newFixedLengthResponse("success"); } return newFixedLengthResponse("404"); } public static Response newFixedLengthResponse(String msg) { return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, msg); } }