注册 X
提交 注:点击提交后系统会发送邮件到邮箱验证!(仅支持中国大陆邮箱)
我已阅读并同意 服务条款
首页 > IT技术笔记 > 查看笔记

轻量级的java HTTP Server——NanoHttpd,Android轻量级http服务器

附件下载:

nanohttp.zip

具体使用:

把代码加入到安卓项目中,或者也可以把源代码打包成jar文件,导入项目

1、新建Http.java继承NanoHTTPD

public class Http extends NanoHTTPD{


MyLog log = null;

private static final String TAG = "Http";

private FragmentActivity activityContext;

public Http(int port,JSONObject config,FragmentActivity activityContext) {

        super(port);

        this.activityContext = activityContext;

if(log == null){

if(config==null){

config = new Utils().getConfig();

}

if(config.get("startLog")!=null && config.get("startLog").toString().equals("t")){

log = new MyLog(Http.class, true);

}else{

log = new MyLog(Http.class, false);

}

}

    }

    @Override

    public Response serve(IHTTPSession session) {

        try {

            // 这一句话必须要写,否则在获取数据时,获取不到数据

            session.parseBody(new HashMap<String, String>());

        } catch (IOException e) {

            e.printStackTrace();

        } catch (ResponseException e) {

            e.printStackTrace();

        }


        StringBuilder builder = new StringBuilder();

        Method method = session.getMethod();

        String uri = session.getUri();

        Map<String, String> parms = session.getParms();

        

        log.i(parms);

        

        String data = parms.get("data");//这里的data是POST提交表单时key

        log.i("method: "+method);

        log.i("uri: "+uri);//如果有uri,会打印出uri

        log.i("data: "+data);

        

        if(uri.equals("/upload")){ //文件上传

        log.i("=====upload=====");

        return saveFile(session, parms, "");

        }else if(uri.equals("/download")){ //文件下载

        Response response = responseFile1(session, parms); //支持视频播放快进

        return response;

        }

        else if(uri.equals("/getFileList")){ //提供文件列表接口

        Response response = responseFileList(session, parms);

        return response;

        }else if(uri.equals("/createNew")){ //提供新建文件或文件夹列表接口

        Response response = responsecreateNew(session, parms);

        return response;

        }else if(uri.equals("/deleteFileOrDir")){ //删除文件

        Response response = responsedeleteFileOrDir(session, parms);

        return response;

        }else if(uri.equals("/getProperties")){ //获取属性

        Response response = responseGetProperties(session, parms);

        return response;

        }else if(uri.equals("/controlPhone")){ //接收指令控制手机

        Response response = responseControlPhone(session, parms);

        return response;

        }else{

         

    if(uri.equals("/")){ //访问主页

    String rs = readAssetsFile("web.html");

    String ip = "";

    try {

        Map<String, String> ipMap = Utils.getLocalIpAddr(); //获取ip地址

                for (Map.Entry<String,String> entry : ipMap.entrySet()) {

                if( StringUtils.isNotBlank(entry.getValue()) && !entry.getValue().equals("127.0.0.1")){

                ip = entry.getValue();

                }

        }

} catch (Exception e) {

e.printStackTrace();

}

    System.out.println("ip:"+ip);

    String localhost = ip+":"+new Utils().getConfig().getString("serverPort");

    System.out.println("localhost:"+localhost);

        rs = rs.replace("127.0.0.1:8888", localhost);


        return Response.newFixedLengthResponse(rs);

    }

   

    //访问controller

    if(uri.contains("Controller")){

    Response response = responseController(session, parms,uri);

   

            return response;

    }

         

        //如果是请求js、css、图片等资源文件

        Map<String, String> map = Utils.getNameAndSuffix(uri);

        String suffix = map.get("suffix");

        if( suffix!=null && (suffix.equals("html")||suffix.equals("js")||suffix.equals("css")||suffix.equals("jpg")||suffix.equals("png")||suffix.equals("gif"))){

       

        if(uri.indexOf("/")==0){

        uri = uri.replaceFirst("/", "");

        }

        String rs = readAssetsFile(uri);

       

        return Response.newFixedLengthResponse(rs);

        }

       

        }


        

        //builder.append("404 not found"); // 反馈给调用者的数据

String rs = readAssetsFile("404.html");

builder.append(rs);

        return Response.newFixedLengthResponse(builder.toString());

        

    }

}


2、在MainActivity开启服务

try {

            int port = 8080;

            Http server = new Http(port,config,activityContext);

            //开启http服务

           server.start();

} catch (Exception e) {

e.printStackTrace();

}


		        
    //对于请求文件的,返回下载的文件
    public Response responseFile1(IHTTPSession session,Map<String, String> parms){
        try {        	
        	String id = parms.get("id");
        	log.i("responseFile1 id is:"+id);
        	String path = "";
        	
        	if(StringUtils.isBlank(id)){
        		path = Utils.unescape(Utils.decodeStr(parms.get("path")));
        	}else{
    			//创建一个DatabaseHelper对象,创建explorer.db数据库
    			DatabaseHelper dbHelper = new DatabaseHelper(activityContext);
    			//获取一个只读的数据库对象
    			SQLiteDatabase db = dbHelper.getReadableDatabase();
    			
            	path = DBUtils.queryFilePathById(db, id);
            	db.close();
        	}
        	

        	// /storage/emulated/0/Download/oceans.mp4
        	log.i("responseFile path is:"+path);
        	File file = new File(path);
        	
        	
        	Map<String,String> map = Utils.getNameAndSuffix(file.getName());
        	String name = map.get("name");		//文件名(不带后缀)
        	String suffix = map.get("suffix");		//文件后缀
        	String mimeType = null;			//返回类型
        	if(suffix.equals("mp4")){
        		mimeType = "video/mpeg4";
        	}else if(suffix.equals("txt")){
        		mimeType = "text/plain";
        	}else{
        		mimeType = "application/octet-stream";		// 二进制流,不知道下载文件类型
        	}
        	
            String range = null;
            
            Map<String, String> headers = session.getHeaders();
            for (String key : headers.keySet()) {
               // Log.e(TAG, key + ":" + headers.get(key) + ", val:" + headers.get(key));
                if ("range".equals(key)) {
                    range = headers.get(key); // 读取range header,包含要返回的媒体流位置等信息。
                }
            }
            Response response = null;
            if (range == null) {

                // 如果range为空,返回该文件的所有媒体流
                //文件输入流
            	FileInputStream fis = new FileInputStream(file);
                // 返回OK,同时传送文件,为了安全这里应该再加一个处理,即判断这个文件是否是我们所分享的文件,避免客户端访问了其他个人文件
            	
            	response = Response.newFixedLengthResponse(Status.OK,mimeType,fis,fis.available());
            	response.addHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(file.getName(), "UTF-8"));//设置头部信息
            	response.addHeader("Content-Length", String.valueOf(file.length()));
              } else {

                 // 根据range参数,返回制定位置的媒体流  

            	  response = getPartialResponse(file, range, mimeType);
            }
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar cd = Calendar.getInstance();
            cd.setTimeZone(TimeZone.getTimeZone("GMT"));
            cd.setTimeInMillis(file.lastModified());
            response.addHeader("Last-Modified", sdf.format(cd.getTime()));
            
            return response;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }    
    
    // 根据range中定义的范围返回媒体流
    private Response getPartialResponse(File file, String rangeHeader, String mimeType) throws IOException {
        String rangeValue = rangeHeader.trim().substring("bytes=".length());
        Response response = null;
        long fileLength = file.length();
        long start, end;
        if (rangeValue.startsWith("-")) {
            end = fileLength - 1;
            start = fileLength - 1
                    - Long.parseLong(rangeValue.substring("-".length()));
        } else {
            String[] range = rangeValue.split("-");
            start = Long.parseLong(range[0]);
            end = range.length > 1 ? Long.parseLong(range[1])
                    : fileLength - 1;
        }
        if (end > fileLength - 1) {
            end = fileLength - 1;
        }

        // 解析range中的start,end位置
    
        InputStream fileInputStream;
        if (start <= end) {
            long contentLength = end - start + 1;
            fileInputStream = new FileInputStream(file);
            fileInputStream.skip(start); //将媒体流跳转到start处,然后返回
            
            response = Response.newFixedLengthResponse(Status.PARTIAL_CONTENT,mimeType,fileInputStream,fileInputStream.available());
            response.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
            response.addHeader("Content-Length", contentLength + "");
            return response;
        } else {
        	long contentLength = end - start + 1;
            fileInputStream = new FileInputStream(file);
            fileInputStream.skip(end); //将媒体流跳转到start处,然后返回
            
            //return new Response(Status.RANGE_NOT_SATISFIABLE, MIME_HTML, rangeHeader);
            response = Response.newFixedLengthResponse(Status.RANGE_NOT_SATISFIABLE,mimeType,fileInputStream,fileInputStream.available());
            response.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
            response.addHeader("Content-Length", contentLength + "");
        }
        return response;
    }

    //文件上传,接收文件保存
    public Response saveFile(IHTTPSession session,Map<String, String> parms,String savePath){
    	try {
    		savePath = Utils.unescape(Utils.decodeStr(parms.get("toPath")));
    		String fileName = Utils.unescape(Utils.decodeStr(parms.get("filename")));
    		long filelength = Long.parseLong(parms.get("filelength"));
    		
            for (Map.Entry<String, String> entry : parms.entrySet()) {
                final String paramsKey = entry.getKey();
                log.i("paramsKey:"+paramsKey);
                if (paramsKey.contains("file")) {
            		
                    final String tmpFilePath = parms.get(paramsKey);
                    log.i("tmpFilePath:"+tmpFilePath);
                    File tmpFile = new File(tmpFilePath);
                    final File targetFile = new File(savePath + fileName);
                    
                    
            		String s = System.getProperty("java.io.tmpdir");		//获取上传文件保存的临时目录
            		log.i("====s:"+s);
            		File f = new File(s);
            		File[] files = f.listFiles();
            		for (File f1 : f.listFiles()) {
        				log.i("f1:"+f1.getAbsolutePath()+",len:"+Utils.readableFileSize(f1.length()));
        				if(filelength==f1.length()){
        					tmpFile = f1;									//如果文件大小和上传的文件大小一致,说明是上传的文件
        				}
        			}
                    log.i("copy file now, source file path: "+tmpFile.getAbsoluteFile()+",target file path:"+targetFile.getAbsoluteFile());
                    //a copy file methoed just what you like
                    FileUtils.copyFile(tmpFile, targetFile);
                    //maybe you should put the follow code out
                    return Response.newFixedLengthResponse("success");
                }
            }
		} catch (Exception e) {
			log.e(e.getMessage());
		}
        return Response.newFixedLengthResponse("404,file not found");
    }
		      

 打赏        分享



评论

邮箱: 昵称: