Android 创建服务器 NanoHttpd

android 特殊手机终端创建一个服务器 对外公开地址(生成一个二维码的地址) 扫码识别点开为一个web 页面,可以下载本地的相关资源 或者播放本地的资源

使用NanoHttpd在Android项目中搭建服务器

android 服务器播放视频
其实都大同小异

也可以这种搭建服务器
AndServer,一个Android端的web服务器
这种比较繁琐

我的包直接用的 [android 服务器播放视频] 项目里面的lib

package com.pad.ui.activity.progressbar;



import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Response.Status;


public class FileServer extends NanoHTTPD{

    public static final int DEFAULT_SERVER_PORT= 8080;//为8080
    public static final String TAG = FileServer.class.getSimpleName();
    //根目录
    private static  final String REQUEST_ROOT = "/";
    private List fileList;//用于分享的文件列表



    public FileServer(List fileList) {
        super(DEFAULT_SERVER_PORT);
        this.fileList = fileList;
    }

    @Override
    public Response serve(IHTTPSession session) {
        Log.d(TAG,"OnRequest: "+session.getUri());
        if(REQUEST_ROOT.equals(session.getUri())||session.getUri().equals("")){
            return responseRootPage(session);
        }
        return responseFile(session);
//        return response404(session,session.getUri());
    }
    //对于请求根目录的,返回分享的文件列表
    public Response responseRootPage(IHTTPSession session) {
        StringBuilder builder = new StringBuilder();
        builder.append("");
        builder.append("
    "); for (int i = 0, len = fileList.size(); i < len; i++) { File file = new File(fileList.get(i).getPath()); if (file.exists()) { //文件及下载文件的链接,定义了一个文件类,这里使用getPath方法获得路径,使用getName方法获得文件名 builder.append("
  1. " + file.getName() + "
  2. "); } } builder.append("
  3. File Size: " + fileList.size() + "
  4. "); builder.append("
"); builder.append("\n"); //回送应答 return new Response(String.valueOf(builder)); } //对于请求文件的,返回下载的文件 public Response responseFile(IHTTPSession session){ try { //uri:用于标示文件资源的字符串,这里即是文件路径 String uri = session.getUri(); FileInputStream fis = new FileInputStream(uri); return new Response(Status.OK,"application/octet-stream",fis); } catch (FileNotFoundException e) { e.printStackTrace(); } return response404(session,null); } public Response response404(IHTTPSession session,String url) { StringBuilder builder = new StringBuilder(); builder.append(""); builder.append("Sorry, Can't Found "+url + " !"); builder.append("\n"); return new Response(builder.toString()); } }

activity 主要实现 服务的开启与关闭 随带吧url 生成二维码方便外部访问下载 (同一局域网访问下载)


   private static final String DEFAULT_FILE_PATH = Environment.getExternalStorageDirectory() + "/movie.mp4";
  
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ipStr = getIpAddress(ProgressBarActivity.this);
        String macStr = getMacAddressFromIp(ProgressBarActivity.this);
        showIp.setText("IP : " + ipStr);

        mVideoServer = new VideoServer(DEFAULT_FILE_PATH, VIDEO_WIDTH, VIDEO_HEIGHT, VideoServer.DEFAULT_SERVER_PORT);
        showIp.setText("请在远程浏览器中输入:\n\n" + ipStr + ":" + VideoServer.DEFAULT_SERVER_PORT);
        List sharedFileList = new ArrayList<>();
        SharedFile sharedFile = new SharedFile();
        sharedFile.setName("movie.mp4");
        sharedFile.setPath(DEFAULT_FILE_PATH);
        sharedFileList.add(sharedFile);
        SharedFile sharedFile01 = new SharedFile();
        sharedFile01.setName("人员.xlsx");
        sharedFile01.setPath(Environment.getExternalStorageDirectory() + "/mo.xlsx");
        sharedFileList.add(sharedFile01);

        fileServer = new FileServer(sharedFileList);

        handler.post(new Runnable() {
            @Override
            public void run() {

                Bitmap qrccode = QRCodeEncoder.syncEncodeQRCode(ipStr + ":" + VideoServer.DEFAULT_SERVER_PORT+
                        DEFAULT_FILE_PATH,400);
//                Bitmap qrccode = QRCodeEncoder.syncEncodeQRCode(ipStr + ":" + VideoServer.DEFAULT_SERVER_PORT,200);
                showZxing.setImageBitmap(qrccode);
            }
        });

  @Override
    protected void onDestroy() {
        mVideoServer.stop();
        fileServer.stop();
        super.onDestroy();
    }

    }

手机端 或者网页端直接
http://10.67.13.209:8080/ 类似这种可以看到列表 然后点击可以下载资源

http://10.67.13.209:8080/storage/emulated/0/mo.xlsx

类似这种可以直接下载资源到本地

这个 视频播放 网页端播放视频流

我们N多年前对终端的数据做处理,增删改的操作可以这样做

  @Deprecated
    public Response serve(IHTTPSession session) {
        try {
            if (Method.POST.equals(session.getMethod())) {
                String uri = session.getUri();
                fields = session.getParms();
                session.parseBody(fields);
                String result = "";
                switch (uri) {
                    case "/SendQRPayAddress":
                        receiveAddress();
                        break;
                    case "/SendPlu":
                        receivePLU();
                        break;
                    case "/SendShopName":
                        receiveShopConfig();
                        break;
                    case "/GetTransaction":
                        result = sendTransaction();
                        break;
                    case "/GetTransactionDetail":
                        result = sendTransactionDetail();
                        break;
                    case "/GetPurchaseOrder":
                        result = sendPurchase();
                        break;
                    case "/DeleteAll":
                        dtManager.delete();
                        break;
                    case "/DeleteBySerialNum":
                        deleteTransactionBySerialNum();
                        break;
                    case "/DeleteByTradeTime":
                        deleteTransactionByTime();
                        break;
                    case "/DeleteTransactionByTime":
                        deleteTransaction();
                        break;
                    case "/SendSysTime":
                        DateUtil.setSystemDate(fields.get("Time"));
                        break;
                    case "/RestartApp":
                        restartApp();
                        break;
                    case "/SendUser":
                        receiveCustomer();
                        break;
                    case "/SendWebAddress":
                    case "/SendSettings":
                        receiveSettingConfig();
                        break;
                    case "/GetVersionName":
                        return new NanoHTTPD.Response("1," + App.VersionName + ";");
                    case "/DeleteSysLogByType":
                        deleteSysLogByType();
                        break;
                    case "/DeleteSysLogById":
                        deleteSysLogById();
                        break;
                    case "/DeletePurchaseById":
                        deletePurchaseByIds();
                        break;
                    case "/GetSysLog":
                        result = sendSysLog();
                        break;
                    default:
                        return new NanoHTTPD.Response("0,没有匹配的方法;");
                }
                return new NanoHTTPD.Response("1,OK;" + result);
            } else {
                return new NanoHTTPD.Response("0,no_post;");
            }
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
            return new NanoHTTPD.Response("0," + "客户端错误:" + e.getMessage() + ";");
        }
    }

根据不同的url 做具体的也业务处理

这次有用到了,做个记录省的下次再查看,方便直接用到项目中

根据业务需要是一直开着,还是在适当的时候开启服务,自己看着处理

你可能感兴趣的:(android,源码,android)