How to create nanohttpd server in android?

后端 未结 4 1508
情话喂你
情话喂你 2021-02-09 05:10

Actually ,I had searched some questions and go to the github. But I\'m new ,I cannot understand the example.

I want to create the http server in android so I can access

4条回答
  •  感情败类
    2021-02-09 05:51

    This code working for fine viewing html pages with css class which are in my assesst folders

    androidWebServer.start();
    

    this will start the server below code for server functions

    public class AndroidWebServer extends NanoHTTPD {
    
    Realm realm;
    
    Map parms;
    DBHelper db = new DBHelper(OpenRAP.getContext());
    boolean isStartedHS = MainActivity.isStartedHS;
    private AsyncHttpServer server = new AsyncHttpServer();
    private AsyncServer mAsyncServer = new AsyncServer();
    private String TAG = "androidwebserver";
    Storage storage = new Storage(OpenRAP.getContext());
    public AndroidWebServer(int port) {
        super(port);
    }
    
    
    public AndroidWebServer(String hostname, int port) {
        super(hostname, port);
    }
    
    
    @Override
    public String getHostname() {
        return super.getHostname();
    }
    
    
    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        String uri = session.getUri();
        Map files = new HashMap<>();
        SharedPreferences prefs = OpenRAP.getContext().getSharedPreferences(MainActivity.mypreference, MODE_PRIVATE);
        OpenRAP app = (OpenRAP) OpenRAP.getContext();
        Storage storage = new Storage(OpenRAP.getContext());
        String currentpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/";
        String temp = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/temp/";
        String ecarpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/ecars_files/";
        String xcontent = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/xcontent/";
        String Endpoint = session.getUri();
        if (Endpoint.equals("/")) {
    
            String answer = "";
            try {
                // Open file from SD Card
                File root = Environment.getExternalStorageDirectory().getAbsoluteFile();
                FileReader index = new FileReader(root +
                        "/www/openrap/index.html");
                BufferedReader reader = new BufferedReader(index);
                String line = "";
                while ((line = reader.readLine()) != null) {
                    answer += line;
                }
                reader.close();
            } catch (IOException ioe) {
                Log.w("Httpd", ioe.toString());
            }
            return newFixedLengthResponse(answer);
        }
    

提交回复
热议问题