How do I serve external css, jpg and gif files from Nanohttpd (Nanohttpd run on a normal pc not on Android)?

 ̄綄美尐妖づ 提交于 2019-12-01 08:39:39

问题


In index.html, External css is used and paths to image src are used to request css images from a folder. However the images are not loaded and css style is not applied to the page.

import java.io.*;
import java.util.*;

/**
 * An example of subclassing NanoHTTPD to make a custom HTTP server.
 */
public class HelloServer extends NanoHTTPD
{
    public HelloServer() throws IOException
    {
        super(8080, new File("."));
    }

    public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {

        BufferedReader br = null;
        String msg="";

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("index.html"));

            while ((sCurrentLine = br.readLine()) != null) {
                //System.out.println(sCurrentLine);
                msg = msg + sCurrentLine;
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return new NanoHTTPD.Response( HTTP_OK, MIME_HTML, msg );
    }


    public static void main( String[] args )
    {
        try
        {
            new HelloServer();
        }
        catch( IOException ioe )
        {
            System.err.println( "Couldn't start server:\n" + ioe );
            System.exit( -1 );
        }
        System.out.println( "Listening on port 8080. Hit Enter to stop.\n" );
        try { System.in.read(); } catch( Throwable t ) {};
    }
}

In index.html, External css is used and paths to image src are used to request images from a folder but. However the images are not loaded and css style is not applied to the page.


回答1:


Once you send back the HTML file, the browser will run though and make subsequent requests for the other resources - images, JS files, CSS, etc. What you will need to do is look at the "uri" parameter and that will tell you which file you need to send back to the client. Instead of hard-coding "index.html" you will need to base the filename off what is being requested.



来源:https://stackoverflow.com/questions/18030214/how-do-i-serve-external-css-jpg-and-gif-files-from-nanohttpd-nanohttpd-run-on

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!