如何从Nanohttpd提供外部css,jpg和gif文件(Nanohttpd在普通PC上运行而不是在Android上运行)?

时间:2013-08-03 06:53:03

标签: java nanohttpd

在index.html中,使用外部css,图像src的路径用于从文件夹请求css图像。但是,未加载图像,并且css样式未应用于页面。

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 ) {};
    }
}

在index.html中,使用外部css,图像src的路径用于从文件夹请求图像。但是,未加载图像,并且css样式未应用于页面。

1 个答案:

答案 0 :(得分:1)

一旦你发回HTML文件,浏览器就会运行,然后对其他资源 - 图像,JS文件,CSS等进行后续请求。你需要做的是查看“uri”参数和那个将告诉您需要将哪个文件发送回客户端。不需要对“index.html”进行硬编码,而是需要根据所请求的内容来确定文件名。