Search code examples
javaandroidnanohttpd

How to change address in url (http://localhost:8080/HELLO_WORLD) in NanoHttpd


My query is how to change how to change address in URL (http://localhost:8080/HELLO_WORLD). I change HELLO_WORLD to desire word.

 @Override
public Response serve(IHTTPSession session) {       
    String answer = "";
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(
                new InputStreamReader(appContext.getAssets().open("block.html")));
        // do reading, usually loop until end of file reading
        String mLine;
        while ((mLine = reader.readLine()) != null) {
            //process line
            answer += mLine;

        }
    } catch (IOException e) {
        //log the exception
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                //log the exception
                Log.d("BABAR", "EXception occured in serve()");
            }
        }
    }
    return newFixedLengthResponse(answer);
}

please suggest me how to change


Solution

  • I don´t know if this is what you want, but you can try. You have to follow the steps:

    1- Create a local to store your server files; 2-Then change the response in the class that is implementing the NanoHttp server to something like this:

    @Override
    public Response serve(IHTTPSession session) {
        String answer = "";
        try{
            FileReader filereader = new FileReader(contextoMain.local(localyourstorethefiles)+"/yourfolder/yourfile.html");
        BufferedReader reader = new BufferedReader(filereader);
        String line = "";
        while ((line = reader.readLine()) != null) {
            answer += line;
        }
        reader.close();
    
    }catch(IOException ioe) {
        Log.w("Httpd", ioe.toString());
    }
        return newFixedLengthResponse(answer);
    }
    

    3 - Then, call the localhost:8080 without putting the 8080/yourfolder/yourfile